file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/97/0x5A43AaBb47a328D54857B91E8F89a6CF4aDcEa86/sources/project_/contracts/contracts/ERC20.sol
|
Hook that is called after any transfer of tokens. This includes minting and burning. Calling conditions: - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens has been transferred to `to`. - when `from` is zero, `amount` tokens have been minted for `to`. - when `to` is zero, `amount` of ``from``'s tokens have been burned. - `from` and `to` are never both zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]./
|
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
| 5,018,418 |
./full_match/80001/0x67Fa6DF65cBB1A1687403afd39dc82042892623c/sources/NFTstaking.sol
|
Make sure the user has at least one token staked before withdrawing Wallet must own the token they are trying to withdraw Update the rewards for this user, as the amount of rewards decreases with less tokens Find the index of this token id in the stakedTokens array
|
function withdraw(uint256 _tokenId) external nonReentrant {
require(
stakers[msg.sender].amountStaked > 0,
"You have no tokens staked"
);
require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!");
uint256 rewards = calculateRewards(msg.sender);
stakers[msg.sender].unclaimedRewards += rewards;
uint256 index = 0;
for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) {
if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) {
index = i;
break;
}
}
}
| 9,471,372 |
./partial_match/1/0x5676f6b5563c157EbF68b2a113c3F0152B5fB91E/sources/HalfAveAccessPasses.sol
|
Allows owner of the collection to airdrop a token to any address
|
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_safeMint(_receiver, _mintAmount);
}
| 3,719,246 |
/**
*Submitted for verification at Etherscan.io on 2021-11-20
*/
// 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: contracts/365 Space Project NEW.sol
pragma solidity ^0.8.0;
contract Project365Space is ERC721Enumerable, Ownable {
using Strings for uint256;
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private tokenIdsCounter;
enum SaleStage { sale1, sale2 } // ids are 0, 1
SaleStage public saleStage = SaleStage.sale1; // Default to other
mapping(uint => uint256) numTokensSoldByStage; // Number of tokens sold by each stage
mapping(uint => uint256) maxCapByStage; // Max tokens that can be minted in sale stage
string public baseURI; // Base URI for json files
string public baseExtension = ".json"; // extension for tokenURI files
string public notRevealedUri;
uint256 public cost = 0.07 ether; // Cost per NFT
uint256 public maxSupply = 5110;
uint256 public maxMintAmount = 10; // Maximum number of tokens can be minted in single transaction
bool public paused = false;
bool public isSaleActive = false;
bool public revealed = false;
bool public allowOnlyWhitelisted = false;
address[] public whitelistedAddresses;
constructor(
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721("365 Space Project", "SPACE") {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
// Initialise max cap for sale stages
maxCapByStage[uint(SaleStage.sale1)] = 1000;
maxCapByStage[uint(SaleStage.sale2)] = 4000;
}
/**
* reserve NFTs to given address
*/
function reserve(address _to, uint _numOfNfts) public onlyOwner {
uint256 supply = totalSupply();
require(!paused, "Contract paused!");
require(_to != address(0), "_to address cannot be dead address!");
require(_numOfNfts > 0);
require(supply.add(_numOfNfts) <= maxSupply, "MaxSupply exceeding!");
for (uint256 i = 1; i <= _numOfNfts; i++) {
tokenIdsCounter.increment();
_safeMint(_to, tokenIdsCounter.current());
}
}
function getMaxCapForStage(uint _stage) public view returns (uint256) {
return maxCapByStage[_stage];
}
function getNumberOfTokensSoldByStage(uint _stage) public view returns (uint256) {
return numTokensSoldByStage[_stage];
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(address _to, uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused, "Contract paused!");
require(_to != address(0), "_to address cannot be dead address!");
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount, "_mintAmount exceeds max maxMintAmount!");
require(supply.add(_mintAmount) <= maxSupply, "MaxSupply exceeding!");
if (msg.sender != owner()) {
require(isSaleActive, "Sale is inactive");
if (allowOnlyWhitelisted == true) {
require(isWhitelisted(msg.sender), "user is not whitelisted");
}
require(msg.value >= cost.mul(_mintAmount), "Not enough ethers sent to mint NFTs!");
}
if (isSaleActive) {
uint256 _totalSell = numTokensSoldByStage[uint(saleStage)].add(_mintAmount);
require(_totalSell <= maxCapByStage[uint(saleStage)], "_mintAmount exceeding max cap for current sale!");
// Update token sold count
numTokensSoldByStage[uint(saleStage)] = numTokensSoldByStage[uint(saleStage)].add(_mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
tokenIdsCounter.increment();
_safeMint(_to, tokenIdsCounter.current());
}
}
function isWhitelisted(address _user) public view returns (bool) {
for (uint i = 0; i < whitelistedAddresses.length; i++) {
if (whitelistedAddresses[i] == _user) {
return true;
}
}
return false;
}
/**
* @dev get tokenIds of _account address
*/
function walletOfOwner(address _account)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_account);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_account, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)
)
: "";
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused, "ERC721Pausable: token transfer while paused");
}
//only owner
function reveal() public onlyOwner {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setmaxCapForStage(uint _stage, uint256 _maxCap) public onlyOwner() {
maxCapByStage[_stage] = _maxCap;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setIsSaleActive(bool _state) public onlyOwner {
isSaleActive = _state;
}
/**
* @dev Allows admin to update the sale stage
* @param _stage sale stage
*/
function setSaleStage(uint _stage) public onlyOwner {
if(uint(SaleStage.sale1) == _stage) {
saleStage = SaleStage.sale1;
cost = 0.07 ether;
} else if (uint(SaleStage.sale2) == _stage) {
saleStage = SaleStage.sale2;
cost = 0.09 ether;
}
}
function setAllowOnlyWhitelisted(bool _state) public onlyOwner {
allowOnlyWhitelisted = _state;
}
function whitelistUsers(address[] calldata _users) public onlyOwner {
delete whitelistedAddresses;
whitelistedAddresses = _users;
}
/**
* @dev Withdraw ethers available on contract to the callers address
*/
function withdraw() public payable onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
}
|
public Update token sold count
|
function mint(address _to, uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused, "Contract paused!");
require(_to != address(0), "_to address cannot be dead address!");
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount, "_mintAmount exceeds max maxMintAmount!");
require(supply.add(_mintAmount) <= maxSupply, "MaxSupply exceeding!");
if (msg.sender != owner()) {
require(isSaleActive, "Sale is inactive");
if (allowOnlyWhitelisted == true) {
require(isWhitelisted(msg.sender), "user is not whitelisted");
}
require(msg.value >= cost.mul(_mintAmount), "Not enough ethers sent to mint NFTs!");
}
if (isSaleActive) {
uint256 _totalSell = numTokensSoldByStage[uint(saleStage)].add(_mintAmount);
require(_totalSell <= maxCapByStage[uint(saleStage)], "_mintAmount exceeding max cap for current sale!");
numTokensSoldByStage[uint(saleStage)] = numTokensSoldByStage[uint(saleStage)].add(_mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
tokenIdsCounter.increment();
_safeMint(_to, tokenIdsCounter.current());
}
}
| 6,819,720 |
pragma solidity ^0.4.21;
// Interface to ERC20 functions used in this contract
interface ERC20token {
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
contract ExoTokensSwap{
ERC20token TokenFrom;
ERC20token TokenTo;
address owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
}
function setERC20TokenFrom(address tokenAddr) public onlyOwner {
TokenFrom = ERC20token(tokenAddr);
}
function getERC20TokenFrom() public view returns(address) {
return TokenFrom;
}
function setERC20TokenTo(address tokenAddr) public onlyOwner {
TokenTo = ERC20token(tokenAddr);
}
function getERC20TokenTo() public view returns(address) {
return TokenTo;
}
function getERC20BalanceFrom() public view returns(uint256) {
return TokenFrom.balanceOf(this);
}
function getERC20BalanceTo() public view returns(uint256) {
return TokenTo.balanceOf(this);
}
function swapERC20Token(uint256 fromAmount) public returns(uint){
require(fromAmount > 0);
require (TokenFrom.allowance(msg.sender, this) >= fromAmount);
uint256 wallet_tokenTo_balance = TokenTo.balanceOf(this);
require(wallet_tokenTo_balance >= fromAmount); // must be more in the contract than what user wants to swap
require(TokenFrom.transferFrom(msg.sender, this, fromAmount)); // Take erc20 tokens from sender
require(TokenTo.transfer(msg.sender, fromAmount)); // send erc20 to sender
}
function moveERC20Tokens(address _tokenContract, address _to, uint _val) public onlyOwner {
ERC20token token = ERC20token(_tokenContract);
require(token.transfer(_to, _val));
}
// Allows the owner to move any ether on address
function moveEther(address _target, uint256 _amount) public onlyOwner {
require(_amount <= address(this).balance);
_target.transfer(_amount);
}
// change the owner
function setOwner(address _owner) public onlyOwner {
owner = _owner;
}
// empty fallback payable to allow ETH deposits to the contract
function() public payable{
}
}
|
empty fallback payable to allow ETH deposits to the contract
|
function() public payable{
}
| 12,809,801 |
./full_match/80001/0x20f4B1793bb81FFa357E1705AD954BdC232Edc00/sources/project_/contracts/WittyPixelsToken.sol
|
Fractionalize given token by transferring ownership to new instance of ERC-20 ERC721Token Vault. This vault factory is only intended for fractionalizing its own tokens.
|
function fractionalize(address, uint256, bytes memory)
external pure
override
returns (ITokenVault)
{
revert("WittyPixelsToken: not implemented");
}
| 5,590,304 |
./full_match/80001/0x7A9f65E8989d92ca200CE08839d90F3411088757/sources/contracts/Main.sol
|
uint dF = (A_dS) + (B/3)( S3 - (S - _dS)3 );
|
function sellPrice(uint _dS) public view returns(uint) {
uint dF = 1000 * (sqrt(S**2+10**6)-sqrt((S-_dS)**2+10**6));
return dF;
}
| 852,210 |
./full_match/41/0x83A59050218A540C6e7C4380695Dc804F52F56D7/sources/contracts/ZombieVan.sol
|
Add, edit or remove an NFT collection. To remove a collection, set its multiplier to 0. Add a new NFT collection Edit the NFT collection Remove the NFT collection by swapping it to the last element, then pop it Replace the actual index values with the last ones of the array
|
function setNftCollection(address nftAddress, uint256 multiplier) external onlyOwner {
uint256 index = getNftCollectionIndex(nftAddress);
if (index == uint256(-1)) {
nftAddresses.push(nftAddress);
nftMultipliers.push(multiplier);
_nftCollections.push(IERC721(nftAddress));
if (multiplier > 0) {
nftMultipliers[index] = multiplier;
uint256 lastIndex = nftAddresses.length - 1;
if (lastIndex > 0) {
nftAddresses[index] = nftAddresses[lastIndex];
nftMultipliers[index] = nftMultipliers[lastIndex];
_nftCollections[index] = _nftCollections[lastIndex];
}
nftAddresses.pop();
nftMultipliers.pop();
_nftCollections.pop();
}
}
}
| 16,370,758 |
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/utils/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
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
/**
* @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
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/CryptoCopyCats.sol
/**
* @title CryptoCopyCats contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract CryptoCopyCats is ERC721, Ownable {
using SafeMath for uint256;
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public maxToMint;
uint256 public MAX_CRYPTO_COPY_CATS_SUPPLY;
uint256 public REVEAL_TIMESTAMP;
string private prerevealURI;
string private specialTokenURI;
string public PROVENANCE_HASH = "";
bool public saleIsActive;
bool public whitelistActive;
bytes32[] _rootHash;
address wallet1;
address wallet2;
mapping(uint256 => uint256) private mintNumberToSpecialToken;
mapping(uint256 => uint256) private replacedTokenNumber;
mapping(address => uint256) public numberOfWhitelistMints;
uint256 maxWhitelistMints;
uint256 maxSpecialTokens;
uint256 numberOfSpecialTokensMinted;
uint256 public discountPrice;
uint256 public fullPrice;
constructor() ERC721("Crypto Copy Cats", "CCCATS") {
MAX_CRYPTO_COPY_CATS_SUPPLY = 2510;
REVEAL_TIMESTAMP = block.timestamp + 3 days; //block.timestamp + 3 days;
specialTokenURI = "https://cryptocopycats.mypinata.cloud/ipfs/QmcP7jLdm6vEs5jFwvUkWUJRBwzcTW6wwtLtVCvvuS6uBT";
prerevealURI = "https://cryptocopycats.mypinata.cloud/ipfs/QmSe33Sr6E5oDoCLvzouaLzJ8y3wiFgevkRmTQnAnrwGcm";
discountPrice = 65000000000000000; // 0.065 Ether
fullPrice = 75000000000000000; // 0.075 Ether
numberOfSpecialTokensMinted = 0;
maxSpecialTokens = 10;
maxToMint = 4;
maxWhitelistMints = 4;
saleIsActive = false;
whitelistActive = false;
wallet1 = 0x6F10Cdb4901bA272dabbF7a6343A8FE43ec7d460; // ccc payout wallet
wallet2 = 0xaf6e1747779744c1CE875A6463e28A5086084ae7; // byt payout wallet
_rootHash = new bytes32[](2);
_rootHash[0] = 0x435bffa06fdde9f30f2df9afc8937f180217f3a782ef6aa88f0c39326ed0f4b7;
_rootHash[1] = 0x1736b74100da5d87fc309b6fb4e084dbd9d21a488951d37cab89c323ebbfb483;
}
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function isTokenEthRedeemable(uint256 tokenId) external view returns(bool)
{
require(startingIndex > 0, "Tokens have not revealed yet");
if(mintNumberToSpecialToken[tokenId] > 0)
{
return true;
}
return false;
}
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function updateRootHash(bytes32 rootHash) external onlyOwner {
_rootHash[1] = rootHash;
}
/**
* Set whitelist price to mint a Crypto Copy Cat.
*/
function setDiscountPrice(uint256 _price) external onlyOwner {
discountPrice = _price;
}
/**
* Set public price to mint a Crypto Copy Cat.
*/
function setFullPrice(uint256 _price) external onlyOwner {
fullPrice = _price;
}
function getTotalWhitelistPrice(uint256 numberOfTokens) internal view returns(uint256) {
uint256 ownedTokens = numberOfWhitelistMints[_msgSender()];
if (ownedTokens == 0) {
return discountPrice.mul(numberOfTokens - 1);
} else {
return discountPrice.mul(numberOfTokens);
}
}
/**
* Set maximum count to mint per txn.
*/
function setMaxToMint(uint256 _maxValue) external onlyOwner {
maxToMint = _maxValue;
}
/**
* Mint Crypto Copy Cat by owner.
*/
function reserveCryptoCopyCat(address _to, uint256 _numberOfTokens) external onlyOwner {
require(_to != address(0), "Invalid address to reserve.");
uint256 supply = totalSupply();
uint256 i;
//Mint address, 0 on first mint
//Supply is 1 so mint tokenId = 1 (which is the 2nd token)
for (i = 0; i < _numberOfTokens; i++) {
_safeMint(_to, supply + i);
}
}
/**
* Set reveal timestamp when finished the sale.
*/
function setRevealTimestamp(uint256 _revealTimeStamp) external onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
function setBaseURI(string memory baseURI) external onlyOwner {
_setBaseURI(baseURI);
}
/**
* External function to set the prereveal URI for all token IDs.
* This is the URI that is shown on each token until the REVEAL_TIMESTAMP
* is surpassed.
*/
function setPrerevealURI(string memory prerevealURI_) external onlyOwner {
prerevealURI = prerevealURI_;
}
/**
* Returns the proper tokenURI only after the startingIndex is finalized.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(startingIndex != 0 && block.timestamp >= REVEAL_TIMESTAMP)
{
string memory base = baseURI();
if (mintNumberToSpecialToken[tokenId] != 0) {
return specialTokenURI;
} else if (replacedTokenNumber[tokenId] != 0){
return string(abi.encodePacked(base, uint2str(replacedTokenNumber[tokenId])));
} else {
string memory tokenURIWithOffset = uint2str(((tokenId + startingIndex) % MAX_CRYPTO_COPY_CATS_SUPPLY));
return string(abi.encodePacked(base, tokenURIWithOffset));
}
}
else
{
return prerevealURI;
}
}
/*
* Pause sale if active, make active if paused
*/
function setSaleState() external onlyOwner {
saleIsActive = !saleIsActive;
}
/*
* Pause whitelist if active, make active if paused
*/
function setWhitelistState() external onlyOwner
{
whitelistActive = !whitelistActive;
}
function isSpecialToken(uint256 tokenId) internal view returns (bool) {
if(numberOfSpecialTokensMinted == maxSpecialTokens){
return false;
} else if((maxSpecialTokens - numberOfSpecialTokensMinted) == (MAX_CRYPTO_COPY_CATS_SUPPLY - totalSupply())) {
return true;
}
uint256 rando = random(string(abi.encodePacked(block.number, block.timestamp, _msgSender(), tokenId)));
if ((rando % 2510) > 2496) {
return true;
} else {
return false;
}
}
/**
* Mints tokens
*/
function mintCryptoCopyCat(uint256 numberOfTokens) external payable {
require(saleIsActive, "Sale must be active to mint");
require(numberOfTokens <= maxToMint, "Invalid amount to mint per once");
require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_COPY_CATS_SUPPLY, "Purchase would exceed max supply");
require(fullPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
if (numberOfTokens > 1) {
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 tokenId = totalSupply();
if (isSpecialToken(tokenId)){
setSpecialToken(tokenId);
}
_safeMint(_msgSender(), tokenId);
}
} else {
uint256 tokenId = totalSupply();
if (isSpecialToken(tokenId)){
setSpecialToken(tokenId);
}
_safeMint(_msgSender(), tokenId);
}
// If we haven't set the starting index and this is either
// 1) the last saleable token or 2) the first token to be sold after
// the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_CRYPTO_COPY_CATS_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* Mints whitelisted tokens
*/
function whitelistMintCryptoCopyCat(uint256 numberOfTokens, uint256 spotInWhitelist, bytes32[] memory proof) external payable {
require(whitelistActive, "The whitelist is not active yet");
require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_COPY_CATS_SUPPLY, "Purchase would exceed max supply");
require(numberOfTokens <= maxToMint, "Invalid amount to mint per once");
require(whitelistValidated(_msgSender(), spotInWhitelist, proof), "You're not on the whitelist");
require((numberOfWhitelistMints[_msgSender()] + numberOfTokens) <= maxWhitelistMints, "This transaction exceeds the max whitelist mints");
require(getTotalWhitelistPrice(numberOfTokens) == msg.value, "Ether value sent is not correct");
//Update numberOfWhitelistMints for the wallet
numberOfWhitelistMints[_msgSender()] += numberOfTokens;
if (numberOfTokens > 1) {
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 tokenId = totalSupply();
if (isSpecialToken(tokenId)){
setSpecialToken(tokenId);
}
_safeMint(_msgSender(), tokenId);
}
} else {
uint256 tokenId = totalSupply();
if (isSpecialToken(tokenId)){
setSpecialToken(tokenId);
}
_safeMint(_msgSender(), tokenId);
}
}
function setSpecialToken(uint256 tokenId) internal {
uint256 specialTokenNumber = SafeMath.add(2500, numberOfSpecialTokensMinted);
mintNumberToSpecialToken[tokenId] = specialTokenNumber;
replacedTokenNumber[specialTokenNumber] = tokenId;
numberOfSpecialTokensMinted++;
}
function whitelistValidated(address wallet, uint256 index, bytes32[] memory proof) internal view returns (bool) {
uint256 amount = 1;
// Compute the merkle root
bytes32 node = keccak256(abi.encodePacked(index, wallet, amount));
uint256 path = index;
for (uint16 i = 0; i < proof.length; i++) {
if ((path & 0x01) == 1) {
node = keccak256(abi.encodePacked(proof[i], node));
} else {
node = keccak256(abi.encodePacked(node, proof[i]));
}
path /= 2;
}
// Check the merkle proof against the root hash array
for(uint i = 0; i < _rootHash.length; i++)
{
if (node == _rootHash[i])
{
return true;
}
}
return false;
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() external {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_CRYPTO_COPY_CATS_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint256(blockhash(block.number - 1)) % MAX_CRYPTO_COPY_CATS_SUPPLY;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() external onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
uint256 walletBalance = balance.mul(93).div(100);
payable(wallet1).transfer(walletBalance);
payable(wallet2).transfer(balance.sub(walletBalance));
}
}
|
Set whitelist price to mint a Crypto Copy Cat./
|
function setDiscountPrice(uint256 _price) external onlyOwner {
discountPrice = _price;
}
| 1,102,321 |
./full_match/1/0xcb52eE1e1ae95A0E2917aD48F5693623F0d2273C/sources/contracts/darkz.sol
|
Set provenance once it's calculated/
|
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
DARKZ_PROVENANCE = provenanceHash;
}
| 3,022,840 |
// File: contracts/zeppelin/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @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;
}
}
// File: contracts/ZTUSDImplementation.sol
pragma solidity ^0.4.24;
pragma experimental "v0.5.0";
/**
* @title ZTUSDImplementation
* @dev this contract is a Pausable ERC20 token with Burn and Mint
* controleld by a central SupplyController. By implementing Zap Theory Implementation
* this contract also includes external methods for setting
* a new implementation contract for the Proxy.
* NOTE: The storage defined here will actually be held in the Proxy
* contract and all calls to this contract should be made through
* the proxy, including admin actions done as owner or supplyController.
* Any call to transfer against this contract should fail
* with insufficient funds since no tokens will be issued there.
*/
contract ZTUSDImplementation {
/**
* MATH
*/
using SafeMath for uint256;
/**
* DATA
*/
// INITIALIZATION DATA
bool private initialized = false;
// ERC20 BASIC DATA
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
string public constant name = "ZTUSD"; // solium-disable-line uppercase
string public constant symbol = "ZTUSD"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
// ERC20 DATA
mapping (address => mapping (address => uint256)) internal allowed;
// OWNER DATA
address public owner;
// PAUSABILITY DATA
bool public paused = false;
// EMERGENCY CONTROLLER DATA
address public emergencyControllerRole;
mapping(address => bool) internal frozen;
// SUPPLY CONTROL DATA
address public supplyController;
/**
* EVENTS
*/
// ERC20 BASIC EVENTS
event Transfer(address indexed from, address indexed to, uint256 value);
// ERC20 EVENTS
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
// OWNABLE EVENTS
event OwnershipTransferred(
address indexed oldOwner,
address indexed newOwner
);
// PAUSABLE EVENTS
event Pause();
event Unpause();
// EMERGENCY CONTROLLER EVENTS
event AddressFrozen(address indexed addr);
event AddressUnfrozen(address indexed addr);
event FrozenAddressWiped(address indexed addr);
event EmergencyControllerRoleSet (
address indexed oldEmergencyControllerRole,
address indexed newEmergencyControllerRole
);
// SUPPLY CONTROL EVENTS
event SupplyIncreased(address indexed to, uint256 value);
event SupplyDecreased(address indexed from, uint256 value);
event SupplyControllerSet(
address indexed oldSupplyController,
address indexed newSupplyController
);
/**
* FUNCTIONALITY
*/
// INITIALIZATION FUNCTIONALITY
/**
* @dev sets 0 initials tokens, the owner, and the supplyController.
* this serves as the constructor for the proxy but compiles to the
* memory model of the Implementation contract.
*/
function initialize() public {
require(!initialized, "already initialized");
owner = msg.sender;
emergencyControllerRole = address(0);
totalSupply_ = 0;
supplyController = msg.sender;
initialized = true;
}
/**
* The constructor is used here to ensure that the implementation
* contract is initialized. An uncontrolled implementation
* contract might lead to misleading state
* for users who accidentally interact with it.
*/
constructor() public {
initialize();
pause();
}
// ERC20 BASIC FUNCTIONALITY
/**
* @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 whenNotPaused returns (bool) {
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[msg.sender], "address frozen");
require(_value <= balances[msg.sender], "insufficient funds");
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 _addr The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _addr) public view returns (uint256) {
return balances[_addr];
}
// ERC20 FUNCTIONALITY
/**
* @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
whenNotPaused
returns (bool)
{
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen");
require(_value <= balances[_from], "insufficient funds");
require(_value <= allowed[_from][msg.sender], "insufficient allowance");
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 whenNotPaused returns (bool) {
require(!frozen[_spender] && !frozen[msg.sender], "address frozen");
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];
}
// OWNER FUNCTIONALITY
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "onlyOwner");
_;
}
/**
* @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), "cannot transfer ownership to address zero");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
// PAUSABILITY FUNCTIONALITY
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "whenNotPaused");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner {
require(!paused, "already paused");
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner {
require(paused, "already unpaused");
paused = false;
emit Unpause();
}
// EMERGENCY CONTROLLER FUNCTIONALITY
/**
* @dev Sets a new emergency controller role address.
* @param _newEmergencyControllerRole The new address allowed to freeze/unfreeze addresses and seize their tokens.
*/
function setEmergencyControllerRole(address _newEmergencyControllerRole) public {
require(msg.sender == emergencyControllerRole || msg.sender == owner, "only emergencyControllerRole or Owner");
emit EmergencyControllerRoleSet(emergencyControllerRole, _newEmergencyControllerRole);
emergencyControllerRole = _newEmergencyControllerRole;
}
modifier onlyEmergencyControllerRole() {
require(msg.sender == emergencyControllerRole, "onlyEmergencyControllerRole");
_;
}
/**
* @dev Freezes an address balance from being transferred.
* @param _addr The new address to freeze.
*/
function freeze(address _addr) public onlyEmergencyControllerRole {
require(!frozen[_addr], "address already frozen");
frozen[_addr] = true;
emit AddressFrozen(_addr);
}
/**
* @dev Unfreezes an address balance allowing transfer.
* @param _addr The new address to unfreeze.
*/
function unfreeze(address _addr) public onlyEmergencyControllerRole {
require(frozen[_addr], "address already unfrozen");
frozen[_addr] = false;
emit AddressUnfrozen(_addr);
}
/**
* @dev Wipes the balance of a frozen address, burning the tokens
* and setting the approval to zero.
* @param _addr The new frozen address to wipe.
*/
function wipeFrozenAddress(address _addr) public onlyEmergencyControllerRole {
require(frozen[_addr], "address is not frozen");
uint256 _balance = balances[_addr];
balances[_addr] = 0;
totalSupply_ = totalSupply_.sub(_balance);
emit FrozenAddressWiped(_addr);
emit SupplyDecreased(_addr, _balance);
emit Transfer(_addr, address(0), _balance);
}
/**
* @dev Gets the balance of the specified address.
* @param _addr The address to check if frozen.
* @return A bool representing whether the given address is frozen.
*/
function isFrozen(address _addr) public view returns (bool) {
return frozen[_addr];
}
// SUPPLY CONTROL FUNCTIONALITY
/**
* @dev Sets a new supply controller address.
* @param _newSupplyController The address allowed to burn/mint tokens to control supply.
*/
function setSupplyController(address _newSupplyController) public {
require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner");
require(_newSupplyController != address(0), "cannot set supply controller to address zero");
emit SupplyControllerSet(supplyController, _newSupplyController);
supplyController = _newSupplyController;
}
modifier onlySupplyController() {
require(msg.sender == supplyController, "onlySupplyController");
_;
}
/**
* @dev Increases the total supply by minting the specified number of tokens to the supply controller account.
* @param _value The number of tokens to add.
* @return A boolean that indicates if the operation was successful.
*/
function increaseSupply(uint256 _value) public onlySupplyController returns (bool success) {
totalSupply_ = totalSupply_.add(_value);
balances[supplyController] = balances[supplyController].add(_value);
emit SupplyIncreased(supplyController, _value);
emit Transfer(address(0), supplyController, _value);
return true;
}
/**
* @dev Decreases the total supply by burning the specified number of tokens from the supply controller account.
* @param _value The number of tokens to remove.
* @return A boolean that indicates if the operation was successful.
*/
function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) {
require(_value <= balances[supplyController], "not enough supply");
balances[supplyController] = balances[supplyController].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit SupplyDecreased(supplyController, _value);
emit Transfer(supplyController, address(0), _value);
return true;
}
}
|
Sets a new supply controller address. _newSupplyController The address allowed to burn/mint tokens to control supply./
|
function setSupplyController(address _newSupplyController) public {
require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner");
require(_newSupplyController != address(0), "cannot set supply controller to address zero");
emit SupplyControllerSet(supplyController, _newSupplyController);
supplyController = _newSupplyController;
}
| 173,103 |
./full_match/1/0x1D0977e86c70EAbb5c8fD98DB1B08C6d60caa0C1/sources/contracts/engine/GenArt721CoreV2_ENGINE_FLEX.sol
|
Adds external asset dependency for project `_projectId`. _projectId Project to be updated. _cid Asset cid (Content identifier). _dependencyType Asset dependency type. 0 - IPFS 1 - ARWEAVE/
|
function addProjectExternalAssetDependency(
uint256 _projectId,
string calldata _cid,
ExternalAssetDependencyType _dependencyType
)
external
onlyUnlockedProjectExternalAssetDependencies(_projectId)
onlyArtistOrWhitelisted(_projectId)
{
uint24 assetCount = projects[_projectId].externalAssetDependencyCount;
ExternalAssetDependency memory asset = ExternalAssetDependency({
cid: _cid,
dependencyType: _dependencyType
});
projects[_projectId].externalAssetDependencies[assetCount] = asset;
projects[_projectId].externalAssetDependencyCount = assetCount + 1;
emit ExternalAssetDependencyUpdated(
_projectId,
assetCount,
_cid,
_dependencyType,
assetCount + 1
);
}
| 9,648,743 |
pragma solidity ^0.4.24;
/*
ETHEREUM WORLD CUP : 14th June - 15th July 2018 [Russia]
- designed and implemented by Norsefire.
- thanks to Etherguy and oguzhanox for debugging and front-end respectively.
Rules are as follows:
* Entry to the game costs 0.2018 Ether. Use the register function when sending this.
- Any larger or smaller amount of Ether, will be rejected.
* 90% of the entry fee will go towards the prize fund, with 10% forming a fee.
Of this fee, half goes to the developer, and half goes directly to Giveth (giveth.io/donate).
The entry fee is the only Ether you will need to send for the duration of the
tournament, barring the gas you spend for placing predictions.
* Buying an entry allows the sender to place predictions on each game in the World Cup,
barring those which have already kicked off prior to the time a participant enters.
* Predictions can be made (or changed!) at any point up until the indicated kick-off time.
* Selecting the correct result for any given game awards the player one point.
In the first stage, a participant can also select a draw. This is not available from the RO16 onwards.
* If a participant reaches a streak of three or more correct predictions in a row, they receive two points
for every correct prediction from the third game until the streak is broken.
* If a participant reaches a streak of *five* or more correct predictions in a row, they receive four points
for every correct prediction from the fifth game until the streak is broken.
* In the event of a tie, the following algorithm is used to decide rankings:
- Compare the sum totals of the scores over the last 32 games.
- If this produces a draw as well, compare results of the last 16 games.
- This repeats until comparing the results of the final.
- If it's a dead heat throughout, a coin-flip (or some equivalent method) will be used to determine the winner.
Prizes:
FIRST PLACE: 40% of Ether contained within the pot.
SECOND PLACE: 30% of Ether contained within the pot.
THIRD PLACE: 20% of Ether contained within the pot.
FOURTH PLACE: 10% of Ether contained within the pot.
Participant Teams and Groups:
[Group D] AR - Argentina
[Group C] AU - Australia
[Group G] BE - Belgium
[Group E] BR - Brazil
[Group E] CH - Switzerland
[Group H] CO - Colombia
[Group E] CR - Costa Rica
[Group E] CS - Serbia
[Group F] DE - Germany
[Group C] DK - Denmark
[Group A] EG - Egypt
[Group G] EN - England
[Group B] ES - Spain
[Group C] FR - France
[Group D] HR - Croatia
[Group B] IR - Iran
[Group D] IS - Iceland
[Group H] JP - Japan
[Group F] KR - Republic of Korea
[Group B] MA - Morocco
[Group F] MX - Mexico
[Group D] NG - Nigeria
[Group G] PA - Panama
[Group C] PE - Peru
[Group H] PL - Poland
[Group B] PT - Portugal
[Group A] RU - Russia
[Group A] SA - Saudi Arabia
[Group F] SE - Sweden
[Group H] SN - Senegal
[Group G] TN - Tunisia
[Group A] UY - Uruguay
*/
contract ZeroBTCInterface {
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
}
contract ZeroBTCWorldCup {
using SafeMath for uint;
/* CONSTANTS */
address internal constant administrator = 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae;
address internal constant givethAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc;
address internal constant BTCTKNADDR = 0xB6eD7644C69416d67B522e20bC294A9a9B405B31;
ZeroBTCInterface public BTCTKN;
string name = "EtherWorldCup";
string symbol = "EWC";
uint internal constant entryFee = 2018e15;
uint internal constant ninetyPercent = 18162e14;
uint internal constant fivePercent = 1009e14;
uint internal constant tenPercent = 2018e14;
/* VARIABLES */
mapping (string => int8) worldCupGameID;
mapping (int8 => bool) gameFinished;
// Is a game no longer available for predictions to be made?
mapping (int8 => uint) gameLocked;
// A result is either the two digit code of a country, or the word "DRAW".
// Country codes are listed above.
mapping (int8 => string) gameResult;
int8 internal latestGameFinished;
uint internal prizePool;
uint internal givethPool;
uint internal adminPool;
int registeredPlayers;
mapping (address => bool) playerRegistered;
mapping (address => mapping (int8 => bool)) playerMadePrediction;
mapping (address => mapping (int8 => string)) playerPredictions;
mapping (address => int8[64]) playerPointArray;
mapping (address => int8) playerGamesScored;
mapping (address => uint) playerStreak;
address[] playerList;
/* DEBUG EVENTS */
event Registration(
address _player
);
event PlayerLoggedPrediction(
address _player,
int _gameID,
string _prediction
);
event PlayerUpdatedScore(
address _player,
int _lastGamePlayed
);
event Comparison(
address _player,
uint _gameID,
string _myGuess,
string _result,
bool _correct
);
event StartAutoScoring(
address _player
);
event StartScoring(
address _player,
uint _gameID
);
event DidNotPredict(
address _player,
uint _gameID
);
event RipcordRefund(
address _player
);
/* CONSTRUCTOR */
constructor ()
public
{
// First stage games: these are known in advance.
// Thursday 14th June, 2018
worldCupGameID["RU-SA"] = 1; // Russia vs Saudi Arabia
gameLocked[1] = 1528988400;
// Friday 15th June, 2018
worldCupGameID["EG-UY"] = 2; // Egypt vs Uruguay
worldCupGameID["MA-IR"] = 3; // Morocco vs Iran
worldCupGameID["PT-ES"] = 4; // Portugal vs Spain
gameLocked[2] = 1529064000;
gameLocked[3] = 1529074800;
gameLocked[4] = 1529085600;
// Saturday 16th June, 2018
worldCupGameID["FR-AU"] = 5; // France vs Australia
worldCupGameID["AR-IS"] = 6; // Argentina vs Iceland
worldCupGameID["PE-DK"] = 7; // Peru vs Denmark
worldCupGameID["HR-NG"] = 8; // Croatia vs Nigeria
gameLocked[5] = 1529143200;
gameLocked[6] = 1529154000;
gameLocked[7] = 1529164800;
gameLocked[8] = 1529175600;
// Sunday 17th June, 2018
worldCupGameID["CR-CS"] = 9; // Costa Rica vs Serbia
worldCupGameID["DE-MX"] = 10; // Germany vs Mexico
worldCupGameID["BR-CH"] = 11; // Brazil vs Switzerland
gameLocked[9] = 1529236800;
gameLocked[10] = 1529247600;
gameLocked[11] = 1529258400;
// Monday 18th June, 2018
worldCupGameID["SE-KR"] = 12; // Sweden vs Korea
worldCupGameID["BE-PA"] = 13; // Belgium vs Panama
worldCupGameID["TN-EN"] = 14; // Tunisia vs England
gameLocked[12] = 1529323200;
gameLocked[13] = 1529334000;
gameLocked[14] = 1529344800;
// Tuesday 19th June, 2018
worldCupGameID["CO-JP"] = 15; // Colombia vs Japan
worldCupGameID["PL-SN"] = 16; // Poland vs Senegal
worldCupGameID["RU-EG"] = 17; // Russia vs Egypt
gameLocked[15] = 1529409600;
gameLocked[16] = 1529420400;
gameLocked[17] = 1529431200;
// Wednesday 20th June, 2018
worldCupGameID["PT-MA"] = 18; // Portugal vs Morocco
worldCupGameID["UR-SA"] = 19; // Uruguay vs Saudi Arabia
worldCupGameID["IR-ES"] = 20; // Iran vs Spain
gameLocked[18] = 1529496000;
gameLocked[19] = 1529506800;
gameLocked[20] = 1529517600;
// Thursday 21st June, 2018
worldCupGameID["DK-AU"] = 21; // Denmark vs Australia
worldCupGameID["FR-PE"] = 22; // France vs Peru
worldCupGameID["AR-HR"] = 23; // Argentina vs Croatia
gameLocked[21] = 1529582400;
gameLocked[22] = 1529593200;
gameLocked[23] = 1529604000;
// Friday 22nd June, 2018
worldCupGameID["BR-CR"] = 24; // Brazil vs Costa Rica
worldCupGameID["NG-IS"] = 25; // Nigeria vs Iceland
worldCupGameID["CS-CH"] = 26; // Serbia vs Switzerland
gameLocked[24] = 1529668800;
gameLocked[25] = 1529679600;
gameLocked[26] = 1529690400;
// Saturday 23rd June, 2018
worldCupGameID["BE-TN"] = 27; // Belgium vs Tunisia
worldCupGameID["KR-MX"] = 28; // Korea vs Mexico
worldCupGameID["DE-SE"] = 29; // Germany vs Sweden
gameLocked[27] = 1529755200;
gameLocked[28] = 1529766000;
gameLocked[29] = 1529776800;
// Sunday 24th June, 2018
worldCupGameID["EN-PA"] = 30; // England vs Panama
worldCupGameID["JP-SN"] = 31; // Japan vs Senegal
worldCupGameID["PL-CO"] = 32; // Poland vs Colombia
gameLocked[30] = 1529841600;
gameLocked[31] = 1529852400;
gameLocked[32] = 1529863200;
// Monday 25th June, 2018
worldCupGameID["UR-RU"] = 33; // Uruguay vs Russia
worldCupGameID["SA-EG"] = 34; // Saudi Arabia vs Egypt
worldCupGameID["ES-MA"] = 35; // Spain vs Morocco
worldCupGameID["IR-PT"] = 36; // Iran vs Portugal
gameLocked[33] = 1529935200;
gameLocked[34] = 1529935200;
gameLocked[35] = 1529949600;
gameLocked[36] = 1529949600;
// Tuesday 26th June, 2018
worldCupGameID["AU-PE"] = 37; // Australia vs Peru
worldCupGameID["DK-FR"] = 38; // Denmark vs France
worldCupGameID["NG-AR"] = 39; // Nigeria vs Argentina
worldCupGameID["IS-HR"] = 40; // Iceland vs Croatia
gameLocked[37] = 1530021600;
gameLocked[38] = 1530021600;
gameLocked[39] = 1530036000;
gameLocked[40] = 1530036000;
// Wednesday 27th June, 2018
worldCupGameID["KR-DE"] = 41; // Korea vs Germany
worldCupGameID["MX-SE"] = 42; // Mexico vs Sweden
worldCupGameID["CS-BR"] = 43; // Serbia vs Brazil
worldCupGameID["CH-CR"] = 44; // Switzerland vs Costa Rica
gameLocked[41] = 1530108000;
gameLocked[42] = 1530108000;
gameLocked[43] = 1530122400;
gameLocked[44] = 1530122400;
// Thursday 28th June, 2018
worldCupGameID["JP-PL"] = 45; // Japan vs Poland
worldCupGameID["SN-CO"] = 46; // Senegal vs Colombia
worldCupGameID["PA-TN"] = 47; // Panama vs Tunisia
worldCupGameID["EN-BE"] = 48; // England vs Belgium
gameLocked[45] = 1530194400;
gameLocked[46] = 1530194400;
gameLocked[47] = 1530208800;
gameLocked[48] = 1530208800;
// Second stage games and onwards. The string values for these will be overwritten
// as the tournament progresses. This is the order that will be followed for the
// purposes of calculating winning streaks, as per the World Cup website.
// Round of 16
// Saturday 30th June, 2018
worldCupGameID["1C-2D"] = 49; // 1C vs 2D
worldCupGameID["1A-2B"] = 50; // 1A vs 2B
gameLocked[49] = 1530367200;
gameLocked[50] = 1530381600;
// Sunday 1st July, 2018
worldCupGameID["1B-2A"] = 51; // 1B vs 2A
worldCupGameID["1D-2C"] = 52; // 1D vs 2C
gameLocked[51] = 1530453600;
gameLocked[52] = 1530468000;
// Monday 2nd July, 2018
worldCupGameID["1E-2F"] = 53; // 1E vs 2F
worldCupGameID["1G-2H"] = 54; // 1G vs 2H
gameLocked[53] = 1530540000;
gameLocked[54] = 1530554400;
// Tuesday 3rd July, 2018
worldCupGameID["1F-2E"] = 55; // 1F vs 2E
worldCupGameID["1H-2G"] = 56; // 1H vs 2G
gameLocked[55] = 1530626400;
gameLocked[56] = 1530640800;
// Quarter Finals
// Friday 6th July, 2018
worldCupGameID["W49-W50"] = 57; // W49 vs W50
worldCupGameID["W53-W54"] = 58; // W53 vs W54
gameLocked[57] = 1530885600;
gameLocked[58] = 1530900000;
// Saturday 7th July, 2018
worldCupGameID["W55-W56"] = 59; // W55 vs W56
worldCupGameID["W51-W52"] = 60; // W51 vs W52
gameLocked[59] = 1530972000;
gameLocked[60] = 1530986400;
// Semi Finals
// Tuesday 10th July, 2018
worldCupGameID["W57-W58"] = 61; // W57 vs W58
gameLocked[61] = 1531245600;
// Wednesday 11th July, 2018
worldCupGameID["W59-W60"] = 62; // W59 vs W60
gameLocked[62] = 1531332000;
// Third Place Playoff
// Saturday 14th July, 2018
worldCupGameID["L61-L62"] = 63; // L61 vs L62
gameLocked[63] = 1531576800;
// Grand Final
// Sunday 15th July, 2018
worldCupGameID["W61-W62"] = 64; // W61 vs W62
gameLocked[64] = 1531666800;
// Set initial variables.
latestGameFinished = 0;
}
/* PUBLIC-FACING COMPETITION INTERACTIONS */
// Register to participate in the competition. Apart from gas costs from
// making predictions and updating your score if necessary, this is the
// only Ether you will need to spend throughout the tournament.
function register()
public
payable
{
address _customerAddress = msg.sender;
require( !playerRegistered[_customerAddress]
&& tx.origin == _customerAddress);
// Receive the entry fee tokens.
require(BTCTKN.transferFrom(_customerAddress, address(this), entryFee));
registeredPlayers = SafeMath.addint256(registeredPlayers, 1);
playerRegistered[_customerAddress] = true;
playerGamesScored[_customerAddress] = 0;
playerList.push(_customerAddress);
require(playerRegistered[_customerAddress]);
prizePool = prizePool.add(ninetyPercent);
givethPool = givethPool.add(fivePercent);
adminPool = adminPool.add(fivePercent);
emit Registration(_customerAddress);
}
// Make a prediction for a game. An example would be makePrediction(1, "DRAW")
// if you anticipate a draw in the game between Russia and Saudi Arabia,
// or makePrediction(2, "UY") if you expect Uruguay to beat Egypt.
// The "DRAW" option becomes invalid after the group stage games have been played.
function makePrediction(int8 _gameID, string _prediction)
public {
address _customerAddress = msg.sender;
uint predictionTime = now;
require(playerRegistered[_customerAddress]
&& !gameFinished[_gameID]
&& predictionTime < gameLocked[_gameID]);
// No draws allowed after the qualification stage.
if (_gameID > 48 && equalStrings(_prediction, "DRAW")) {
revert();
} else {
playerPredictions[_customerAddress][_gameID] = _prediction;
playerMadePrediction[_customerAddress][_gameID] = true;
emit PlayerLoggedPrediction(_customerAddress, _gameID, _prediction);
}
}
// What is the current score of a given tournament participant?
function showPlayerScores(address _participant)
view
public
returns (int8[64])
{
return playerPointArray[_participant];
}
function seekApproval()
public
returns (bool)
{
BTCTKN.approve(address(this), entryFee);
}
// What was the last game ID that has had an official score registered for it?
function gameResultsLogged()
view
public
returns (int)
{
return latestGameFinished;
}
// Sum up the individual scores throughout the tournament and produce a final result.
function calculateScore(address _participant)
view
public
returns (int16)
{
int16 finalScore = 0;
for (int8 i = 0; i < latestGameFinished; i++) {
uint j = uint(i);
int16 gameScore = playerPointArray[_participant][j];
finalScore = SafeMath.addint16(finalScore, gameScore);
}
return finalScore;
}
// How many people are taking part in the tournament?
function countParticipants()
public
view
returns (int)
{
return registeredPlayers;
}
// Keeping this open for anyone to update anyone else so that at the end of
// the tournament we can force a score update for everyone using a script.
function updateScore(address _participant)
public
{
int8 lastPlayed = latestGameFinished;
require(lastPlayed > 0);
// Most recent game scored for this participant.
int8 lastScored = playerGamesScored[_participant];
// Most recent game played in the tournament (sets bounds for scoring iteration).
mapping (int8 => bool) madePrediction = playerMadePrediction[_participant];
mapping (int8 => string) playerGuesses = playerPredictions[_participant];
for (int8 i = lastScored; i < lastPlayed; i++) {
uint j = uint(i);
uint k = j.add(1);
uint streak = playerStreak[_participant];
emit StartScoring(_participant, k);
if (!madePrediction[int8(k)]) {
playerPointArray[_participant][j] = 0;
playerStreak[_participant] = 0;
emit DidNotPredict(_participant, k);
} else {
string storage playerResult = playerGuesses[int8(k)];
string storage actualResult = gameResult[int8(k)];
bool correctGuess = equalStrings(playerResult, actualResult);
emit Comparison(_participant, k, playerResult, actualResult, correctGuess);
if (!correctGuess) {
// The guess was wrong.
playerPointArray[_participant][j] = 0;
playerStreak[_participant] = 0;
} else {
// The guess was right.
streak = streak.add(1);
playerStreak[_participant] = streak;
if (streak >= 5) {
// On a long streak - four points.
playerPointArray[_participant][j] = 4;
} else {
if (streak >= 3) {
// On a short streak - two points.
playerPointArray[_participant][j] = 2;
}
// Not yet at a streak - standard one point.
else { playerPointArray[_participant][j] = 1; }
}
}
}
}
playerGamesScored[_participant] = lastPlayed;
}
// Invoke this function to get *everyone* up to date score-wise.
// This is probably best used at the end of the tournament, to ensure
// that prizes are awarded to the correct addresses.
// Note: this is going to be VERY gas-intensive. Use it if you're desperate
// to see how you square up against everyone else if they're slow to
// update their own scores. Alternatively, if there's just one or two
// stragglers, you can just call updateScore for them alone.
function updateAllScores()
public
{
uint allPlayers = playerList.length;
for (uint i = 0; i < allPlayers; i++) {
address _toScore = playerList[i];
emit StartAutoScoring(_toScore);
updateScore(_toScore);
}
}
// Which game ID has a player last computed their score up to
// using the updateScore function?
function playerLastScoredGame(address _player)
public
view
returns (int8)
{
return playerGamesScored[_player];
}
// Is a player registered?
function playerIsRegistered(address _player)
public
view
returns (bool)
{
return playerRegistered[_player];
}
// What was the official result of a game?
function correctResult(int8 _gameID)
public
view
returns (string)
{
return gameResult[_gameID];
}
// What was the caller's prediction for a given game?
function playerGuess(int8 _gameID)
public
view
returns (string)
{
return playerPredictions[msg.sender][_gameID];
}
// Lets us calculate what a participants score would be if they ran updateScore.
// Does NOT perform any state update.
function viewScore(address _participant)
public
view
returns (uint)
{
int8 lastPlayed = latestGameFinished;
// Most recent game played in the tournament (sets bounds for scoring iteration).
mapping (int8 => bool) madePrediction = playerMadePrediction[_participant];
mapping (int8 => string) playerGuesses = playerPredictions[_participant];
uint internalResult = 0;
uint internalStreak = 0;
for (int8 i = 0; i < lastPlayed; i++) {
uint j = uint(i);
uint k = j.add(1);
uint streak = internalStreak;
if (!madePrediction[int8(k)]) {
internalStreak = 0;
} else {
string storage playerResult = playerGuesses[int8(k)];
string storage actualResult = gameResult[int8(k)];
bool correctGuess = equalStrings(playerResult, actualResult);
if (!correctGuess) {
internalStreak = 0;
} else {
// The guess was right.
internalStreak++;
streak++;
if (streak >= 5) {
// On a long streak - four points.
internalResult += 4;
} else {
if (streak >= 3) {
// On a short streak - two points.
internalResult += 2;
}
// Not yet at a streak - standard one point.
else { internalResult += 1; }
}
}
}
}
return internalResult;
}
/* ADMINISTRATOR FUNCTIONS FOR COMPETITION MAINTENANCE */
modifier isAdministrator() {
address _sender = msg.sender;
if (_sender == administrator) {
_;
} else {
revert();
}
}
function _btcToken(address _tokenContract) private pure returns (bool) {
return _tokenContract == BTCTKNADDR; // Returns "true" if this is the 0xBTC Token Contract
}
// As new fixtures become known through progression or elimination, they're added here.
function addNewGame(string _opponents, int8 _gameID)
isAdministrator
public {
worldCupGameID[_opponents] = _gameID;
}
// When the result of a game is known, enter the result.
function logResult(int8 _gameID, string _winner)
isAdministrator
public {
require((int8(0) < _gameID) && (_gameID <= 64)
&& _gameID == latestGameFinished + 1);
// No draws allowed after the qualification stage.
if (_gameID > 48 && equalStrings(_winner, "DRAW")) {
revert();
} else {
require(!gameFinished[_gameID]);
gameFinished [_gameID] = true;
gameResult [_gameID] = _winner;
latestGameFinished = _gameID;
assert(gameFinished[_gameID]);
}
}
// Concludes the tournament and issues the prizes, then self-destructs.
function concludeTournament(address _first // 40% Ether.
, address _second // 30% Ether.
, address _third // 20% Ether.
, address _fourth) // 10% Ether.
isAdministrator
public
{
// Don't hand out prizes until the final's... actually been played.
require(gameFinished[64]
&& playerIsRegistered(_first)
&& playerIsRegistered(_second)
&& playerIsRegistered(_third)
&& playerIsRegistered(_fourth));
// Determine 10% of the prize pool to distribute to winners.
uint tenth = prizePool.div(10);
// Determine the prize allocations.
uint firstPrize = tenth.mul(4);
uint secondPrize = tenth.mul(3);
uint thirdPrize = tenth.mul(2);
// Send the first three prizes.
BTCTKN.approve(_first, firstPrize);
BTCTKN.transferFrom(address(this), _first, firstPrize);
BTCTKN.approve(_second, secondPrize);
BTCTKN.transferFrom(address(this), _second, secondPrize);
BTCTKN.approve(_third, thirdPrize);
BTCTKN.transferFrom(address(this), _third, thirdPrize);
// Send the tokens raised to Giveth.
BTCTKN.approve(givethAddress, givethPool);
BTCTKN.transferFrom(address(this), givethAddress, givethPool);
// Send the tokens assigned to developer.
BTCTKN.approve(administrator, adminPool);
BTCTKN.transferFrom(address(this), administrator, adminPool);
// Since there might be rounding errors, fourth place gets everything else.
uint fourthPrize = ((prizePool.sub(firstPrize)).sub(secondPrize)).sub(thirdPrize);
BTCTKN.approve(_fourth, fourthPrize);
BTCTKN.transferFrom(address(this), _fourth, fourthPrize);
selfdestruct(administrator);
}
// The emergency escape hatch in case something has gone wrong.
// Given the small amount of individual coins per participant, it would
// be far more expensive in gas than what's sent back if required.
// You're going to have to take it on trust that I (the dev, duh), will
// sort out refunds. Let's pray to Suarez it doesn't need pulling.
function pullRipCord()
isAdministrator
public
{
uint totalPool = (prizePool.add(givethPool)).add(adminPool);
BTCTKN.approve(administrator, totalPool);
BTCTKN.transferFrom(address(this), administrator, totalPool);
selfdestruct(administrator);
}
/* INTERNAL FUNCTIONS */
// Gateway check - did you send exactly the right amount?
function _isCorrectBuyin(uint _buyin)
private
pure
returns (bool) {
return _buyin == entryFee;
}
// Internal comparison between strings, returning 0 if equal, 1 otherwise.
function compare(string _a, string _b)
private
pure
returns (int)
{
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
/// Compares two strings and returns true if and only if they are equal.
function equalStrings(string _a, string _b) pure private returns (bool) {
return compare(_a, _b) == 0;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function addint16(int16 a, int16 b) internal pure returns (int16) {
int16 c = a + b;
assert(c >= a);
return c;
}
function addint256(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
assert(c >= a);
return c;
}
}
|
What was the last game ID that has had an official score registered for it?
|
function gameResultsLogged()
view
public
returns (int)
{
return latestGameFinished;
}
| 7,826,932 |
./full_match/1/0xF1C7b9A188C071d397ef55440A028321D6D780A0/sources/contracts/BountyV2.sol
|
Approves the Nth submission for a bounty (0-indexed) bounty The ID of the bounty whose submission to approve submission The ID of the submission to approve Un-assessed submissions get their stakes returned. If we've already approved, refund stake. If this address hashes with the submission ID to produce this payload, it is the target.
|
function approveSubmission(uint256 bounty, uint256 submission) external onlyApprover {
bool _foundSubmission = false;
for (uint32 i = _bounties[bounty].queueIndex; i < submissionsCount(bounty); i++) {
if (_foundSubmission) {
SafeERC20.safeTransfer(IERC20(_arkm), _submissions[bounty][i].submitter, _submissions[bounty][i].stake);
}
else if (_submissions[bounty][i].payload == keccak256(abi.encodePacked(submission, _submissions[bounty][i].submitter))) {
_foundSubmission = true;
approveSubmissionAt(bounty, i);
}
else {
rejectSubmission(bounty);
}
}
require(_foundSubmission, "BountyV2: submission not found");
}
| 3,024,008 |
./full_match/3/0x895919AE76eed4E745aEEbcAC69CCf375aE99BC9/sources/Locker.sol
|
Registering the locker with an owner & Password Set up
|
function RegisterLocker(string memory _LockerRegistrationID,string memory _password) public {
if(GetLength() != 0)
revert("The Owner has already a locker registered");
require(bytes(_LockerRegistrationID).length > 0, "Locker Registration ID cannot be null");
owners[msg.sender].ownerAddress = msg.sender;
owners[msg.sender].LockerID = _LockerRegistrationID;
owners[msg.sender].isLocked = false;
require(msg.sender == owners[msg.sender].ownerAddress,"You are unauthorized to set a password to this Locker.");
owners[msg.sender].password = hash(_password);
owners[msg.sender].isLocked = true;
}
| 14,135,157 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
contract Fitup {
address owner;
uint256 public totalBetCount = 0;
uint256 public activeBetCount = 0;
bool active = false;
struct Ngo {
string name;
address organisation;
}
struct Bet {
uint256 amount;
address organisation;
uint256 created_at;
bool active;
}
mapping(address => Bet) public bets;
event BetCreated(address creator, address organisation, uint256 amount);
event BetPayout(
address issuer,
bool success,
address organisation,
uint256 amount
);
Ngo[] public ngos;
event NgoAdded(string name, address organisation);
modifier onlyOwner() {
require(msg.sender == owner, "only owner can call this");
_;
}
constructor() {
owner = msg.sender;
}
function createBet(address organisation) external payable validateBet {
require(doesNgoExist(organisation) == true, "No ngo with this address");
incrementCount();
incrementActiveCount();
uint256 amount = msg.value;
address creator = msg.sender;
uint256 created_at = block.timestamp;
active = true;
bets[creator] = Bet(amount, organisation, created_at, active);
emit BetCreated(msg.sender, organisation, msg.value);
}
function getBet(address _from) external view returns (Bet memory) {
require(bets[_from].amount > 0, "No Bet exists for that Address");
return bets[_from];
}
function payoutBet(bool _success, address _issuer) external onlyOwner {
require(bets[_issuer].amount > 0, "Valus has to be more than 0");
uint256 _amount = bets[_issuer].amount;
address _organisation = bets[_issuer].organisation;
if (_success == true) {
payable(_issuer).transfer(_amount);
} else {
payable(_organisation).transfer(_amount);
}
emit BetPayout(_issuer, _success, _organisation, _amount);
}
function incrementCount() internal {
totalBetCount += 1;
}
// Storing capacity, need to be reviewed!!
function incrementActiveCount() internal {
activeBetCount += 1;
}
modifier validateBet() {
require(msg.value > 0, "The bet value has to be bigger than 0");
_;
}
function addNgo(string memory name, address organisation)
external
onlyOwner
{
ngos.push(Ngo(name, organisation));
emit NgoAdded(name, organisation);
}
function doesNgoExist(address _ngoAddress) public view returns (bool) {
for (uint256 i = 0; i < ngos.length; i++) {
if (ngos[i].organisation == _ngoAddress) {
return true;
}
}
return false;
}
}
|
Storing capacity, need to be reviewed!!
|
function incrementActiveCount() internal {
activeBetCount += 1;
}
| 15,827,009 |
/**
*Submitted for verification at Etherscan.io on 2021-09-06
*/
pragma solidity ^0.5.12;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
interface IMigrate {
function migrate(address addr, uint256 amount) external returns(bool);
}
contract DPRStaking {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 DPR_UNIT = 10 ** 18;
IERC20 public dpr;
uint256 public staking_time = 270 days; // lock for 9 months
uint256 private total_release_time; // linear release in 3 months
// uint256 private reward_time = 0;
uint256 private total_level;
address public owner;
IMigrate public migrate_address;
bool public pause;
mapping (address => uint256) private user_staking_amount;
mapping (address => uint256) private user_release_time;
mapping (address => uint256) private user_claimed_map;
mapping (address => string) private dpr_address_mapping;
mapping (string => address) private address_dpr_mapping;
mapping (address => bool) private user_start_claim;
mapping (address => uint256) private user_staking_time;
//modifiers
modifier onlyOwner() {
require(msg.sender==owner, "DPRStaking: Only owner can operate this function");
_;
}
modifier whenNotPaused(){
require(pause == false, "DPRStaking: Pause!");
_;
}
//events
event Stake(address indexed user, string DPRAddress, uint256 indexed amount);
event StakeChange(address indexed user, uint256 indexed oldAmount, uint256 indexed newAmount);
event OwnerShipTransfer(address indexed oldOwner, address indexed newOwner);
event DPRAddressChange(bytes32 oldAddress, bytes32 newAddress);
event UserInfoChange(address indexed oldUser, address indexed newUser);
event WithdrawAllFunds(address indexed to);
event Migrate(address indexed migrate_address, uint256 indexed migrate_amount);
event MigrateAddressSet(address indexed migrate_address);
event ExtendStakingTime(address indexed addr);
event AdminWithdrawUserFund(address indexed addr);
constructor(IERC20 _dpr) public {
dpr = _dpr;
total_release_time = 90 days; // for initialize
owner = msg.sender;
}
function stake(string calldata DPRAddress, uint256 amount) external whenNotPaused returns(bool){
require(user_staking_amount[msg.sender] == 0, "DPRStaking: Already stake, use addStaking instead");
checkDPRAddress(msg.sender, DPRAddress);
uint256 staking_amount = amount;
dpr.safeTransferFrom(msg.sender, address(this), staking_amount);
user_staking_amount[msg.sender] = staking_amount;
user_staking_time[msg.sender] = block.timestamp;
user_release_time[msg.sender] = block.timestamp + staking_time;
//user_staking_level[msg.sender] = level;
dpr_address_mapping[msg.sender] = DPRAddress;
address_dpr_mapping[DPRAddress] = msg.sender;
emit Stake(msg.sender, DPRAddress, staking_amount);
return true;
}
function addAndExtendStaking(uint256 amount) external whenNotPaused returns(bool) {
require(!canUserClaim(msg.sender), "DPRStaking: Can only claim");
uint256 oldStakingAmount = user_staking_amount[msg.sender];
require(oldStakingAmount > 0, "DPRStaking: Please Stake first");
dpr.safeTransferFrom(msg.sender, address(this), amount);
//update user staking amount
user_staking_amount[msg.sender] = user_staking_amount[msg.sender].add(amount);
user_staking_time[msg.sender] = block.timestamp;
user_release_time[msg.sender] = block.timestamp + staking_time;
emit StakeChange(msg.sender, oldStakingAmount, user_staking_amount[msg.sender]);
return true;
}
function claim() external whenNotPaused returns(bool){
require(canUserClaim(msg.sender), "DPRStaking: Not reach the release time");
require(block.timestamp >= user_release_time[msg.sender], "DPRStaking: Not release period");
if(!user_start_claim[msg.sender]){
user_start_claim[msg.sender] == true;
}
uint256 staking_amount = user_staking_amount[msg.sender];
require(staking_amount > 0, "DPRStaking: Must stake first");
uint256 user_claimed = user_claimed_map[msg.sender];
uint256 claim_per_period = staking_amount.mul(1 days).div(total_release_time);
uint256 time_pass = block.timestamp.sub(user_release_time[msg.sender]).div(1 days);
uint256 total_claim_amount = claim_per_period * time_pass;
if(total_claim_amount >= user_staking_amount[msg.sender]){
total_claim_amount = user_staking_amount[msg.sender];
user_staking_amount[msg.sender] = 0;
}
user_claimed_map[msg.sender] = total_claim_amount;
uint256 claim_this_time = total_claim_amount.sub(user_claimed);
dpr.safeTransfer(msg.sender, claim_this_time);
return true;
}
function transferOwnership(address newOwner) onlyOwner external returns(bool){
require(newOwner != address(0), "DPRStaking: Transfer Ownership to zero address");
owner = newOwner;
emit OwnerShipTransfer(msg.sender, newOwner);
}
//for emergency case, Deeper Offical can help users to modify their staking info
function modifyUserAddress(address user, string calldata DPRAddress) external onlyOwner returns(bool){
require(user_staking_amount[user] > 0, "DPRStaking: User does not have any record");
require(address_dpr_mapping[DPRAddress] == address(0), "DPRStaking: DPRAddress already in use");
bytes32 oldDPRAddressHash = keccak256(abi.encodePacked(dpr_address_mapping[user]));
bytes32 newDPRAddressHash = keccak256(abi.encodePacked(DPRAddress));
require(oldDPRAddressHash != newDPRAddressHash, "DPRStaking: DPRAddress is same");
dpr_address_mapping[user] = DPRAddress;
delete address_dpr_mapping[dpr_address_mapping[user]];
address_dpr_mapping[DPRAddress] = user;
emit DPRAddressChange(oldDPRAddressHash, newDPRAddressHash);
return true;
}
//for emergency case(User lost their control of their accounts), Deeper Offical can help users to transfer their staking info to a new address
function transferUserInfo(address oldUser, address newUser) external onlyOwner returns(bool){
require(oldUser != newUser, "DPRStaking: Address are same");
require(user_staking_amount[oldUser] > 0, "DPRStaking: Old user does not have any record");
require(user_staking_amount[newUser] == 0, "DPRStaking: New user must a clean address");
//Transfer Staking Info
user_staking_amount[newUser] = user_staking_amount[oldUser];
user_release_time[newUser] = user_release_time[oldUser];
//Transfer claim Info
user_claimed_map[newUser] = user_claimed_map[oldUser];
//Transfer address mapping info
address_dpr_mapping[dpr_address_mapping[oldUser]] = newUser;
dpr_address_mapping[newUser] = dpr_address_mapping[oldUser];
user_staking_time[msg.sender] = block.timestamp;
//clear account
clearAccount(oldUser,false);
emit UserInfoChange(oldUser, newUser);
return true;
}
//for emergency case, Deeper Offical have permission to withdraw all fund in the contract
function withdrawAllFund(address token,uint256 amount) external onlyOwner returns(bool){
IERC20(token).safeTransfer(owner,amount);
emit WithdrawAllFunds(owner);
return true;
}
function setPause(bool is_pause) external onlyOwner returns(bool){
pause = is_pause;
return true;
}
function adminWithdrawUserFund(address user) external onlyOwner returns(bool){
require(user_staking_amount[user] >0, "DPRStaking: No staking");
dpr.safeTransfer(user, user_staking_amount[user]);
clearAccount(user, true);
emit AdminWithdrawUserFund(user);
return true;
}
function clearAccount(address user, bool is_clear_address) private{
delete user_staking_amount[user];
delete user_release_time[user];
delete user_claimed_map[user];
// delete user_staking_period_index[user];
// delete user_staking_periods[user];
delete user_staking_time[user];
if(is_clear_address){
delete address_dpr_mapping[dpr_address_mapping[user]];
}
delete dpr_address_mapping[user];
}
function extendStaking() external returns(bool){
require(user_staking_amount[msg.sender] > 0, "DPRStaking: User does not stake");
require(!isUserClaim(msg.sender), "DPRStaking: User start claim");
// Can be extended up to 12 hours before the staking end
//require(block.timestamp >= user_release_time[msg.sender].sub(43200) && block.timestamp <=user_release_time[msg.sender], "DPRStaking: Too early");
user_release_time[msg.sender] = user_release_time[msg.sender] + staking_time;
emit ExtendStakingTime(msg.sender);
return true;
}
function migrate() external returns(bool){
uint256 staking_amount = user_staking_amount[msg.sender];
require(staking_amount >0, "DPRStaking: User does not stake");
require(address(migrate_address) != address(0), "DPRStaking: Staking not start");
clearAccount(msg.sender, true);
dpr.approve(address(migrate_address), uint256(-1));
migrate_address.migrate(msg.sender, staking_amount);
emit Migrate(address(migrate_address), staking_amount);
return true;
}
function setMigrateAddress(address _migrate_address) external onlyOwner returns(bool){
migrate_address = IMigrate(_migrate_address);
emit MigrateAddressSet(_migrate_address);
return true;
}
function checkDPRAddress(address _address, string memory _dprAddress) private{
require(keccak256(abi.encodePacked(dpr_address_mapping[_address])) == bytes32(hex"c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"), "DPRStaking: DPRAddress already set");
require(address_dpr_mapping[_dprAddress] == address(0), "DPRStaking: ETH address already bind an DPRAddress");
}
// function isUserStartRelease(address _user) external view returns(bool){
// return user_start_release[msg.sender];
// }
function getUserDPRAddress(address user) external view returns(string memory){
return dpr_address_mapping[user];
}
function getUserAddressByDPRAddress(string calldata dpr_address) external view returns(address){
return address_dpr_mapping[dpr_address];
}
function getReleaseTime(address user) external view returns(uint256){
return user_release_time[user];
}
function getStaking(address user) external view returns(uint256){
return user_staking_amount[user];
}
function getUserReleasePerDay(address user) external view returns(uint256){
uint256 staking_amount = user_staking_amount[user];
uint256 release_per_day = staking_amount.mul(1 days).div(total_release_time);
return release_per_day;
}
function getUserClaimInfo(address user) external view returns(uint256){
return user_claimed_map[user];
}
function getReleaseTimeInDays() external view returns(uint256){
return total_release_time.div(1 days);
}
function getUserStakingTime(address user) external view returns(uint256){
return user_staking_time[user];
}
function canUserClaim(address user) public view returns(bool){
return block.timestamp >= (user_staking_time[user] + staking_time);
}
function isUserClaim(address user) public view returns(bool){
return user_start_claim[user];
}
}
|
for emergency case, Deeper Offical have permission to withdraw all fund in the contract
|
function withdrawAllFund(address token,uint256 amount) external onlyOwner returns(bool){
IERC20(token).safeTransfer(owner,amount);
emit WithdrawAllFunds(owner);
return true;
}
| 7,979,853 |
./full_match/40/0x568367728d9588a090a3482c724157C0E05737cc/sources/contracts/IceCreamZombies.sol
|
Change the json filename of a tokenId (should not be used, just in case)
|
function setTokenURI(uint256 id, string calldata dotJson) external onlyOwner {
_setTokenURI(id, dotJson);
emit TokenUriUpdated(id, dotJson);
}
| 9,544,701 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "openzeppelin-contracts/contracts/interfaces/IERC1271.sol";
import "openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "openzeppelin-contracts/contracts/utils/Address.sol";
import "../interfaces/IERC721Permit.sol";
/// @title ERC721 with permit
/// @notice Nonfungible tokens that support an approve via signature, i.e. permit
abstract contract ERC721Permit is ERC721, IERC721Permit {
/// @dev Gets the current nonce for a token ID and then increments it, returning the original value
function _getAndIncrementNonce(uint256 tokenId) internal virtual returns (uint256);
/// @dev The hash of the name used in the permit signature verification
bytes32 private immutable namehash;
/// @dev The chain id that was set at deployment.
uint256 internal immutable chainid_;
/// @dev The domain separator that was set at deployment.
bytes32 internal immutable domainseparator_;
/// @notice Computes the namehash
constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {
namehash = keccak256(bytes(name_));
chainid_ = block.chainid;
domainseparator_ = _domainseparator(block.chainid);
}
/// @notice Returns the permit typehash.
function PERMIT_TYPEHASH() public pure returns (bytes32) {
return keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
}
/// @inheritdoc IERC721Permit
function DOMAIN_SEPARATOR() public view returns (bytes32) {
return block.chainid == chainid_ ? domainseparator_ : _domainseparator(block.chainid);
}
/// @dev Override function to change version.
function version() public pure virtual returns(string memory) {
return "1";
}
/// @inheritdoc IERC721Permit
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
require(block.timestamp <= deadline, 'Permit expired');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
PERMIT_TYPEHASH(),
spender,
tokenId,
_getAndIncrementNonce(tokenId),
deadline
)
)
)
);
address owner = ownerOf(tokenId);
require(spender != owner, 'ERC721Permit: approval to current owner');
if (Address.isContract(owner)) {
require(IERC1271(owner).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, 'Unauthorized');
} else {
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), 'Invalid signature');
require(recoveredAddress == owner, 'Unauthorized');
}
_approve(spender, tokenId);
}
/// @dev Compute the DOMAIN_SEPARATOR.
function _domainseparator(uint256 chainid) internal view returns (bytes32) {
return keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
namehash,
keccak256(bytes(version())),
chainid,
address(this)
)
);
}
}
|
@inheritdoc IERC721Permit
|
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
require(block.timestamp <= deadline, 'Permit expired');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
PERMIT_TYPEHASH(),
spender,
tokenId,
_getAndIncrementNonce(tokenId),
deadline
)
)
)
);
address owner = ownerOf(tokenId);
require(spender != owner, 'ERC721Permit: approval to current owner');
if (Address.isContract(owner)) {
require(IERC1271(owner).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, 'Unauthorized');
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), 'Invalid signature');
require(recoveredAddress == owner, 'Unauthorized');
}
_approve(spender, tokenId);
}
| 5,376,916 |
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
/**
* Based on https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v3.4.0-solc-0.7/contracts/access/OwnableUpgradeable.sol
*
* Changes:
* - Added owner argument to initializer
* - Reformatted styling in line with this repository.
*/
/*
The MIT License (MIT)
Copyright (c) 2016-2020 zOS Global Limited
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.
*/
/* solhint-disable func-name-mixedcase */
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init(address owner_) internal initializer {
__Context_init_unchained();
__Ownable_init_unchained(owner_);
}
function __Ownable_init_unchained(address owner_) internal initializer {
_owner = owner_;
emit OwnershipTransferred(address(0), owner_);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
/**
* Based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0-solc-0.7/contracts/utils/EnumerableMap.sol
*
* Changes:
* - Replaced UintToAddressMap with AddressToUintMap
* - Reformatted styling in line with this repository.
*/
/*
The MIT License (MIT)
Copyright (c) 2016-2020 zOS Global Limited
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.
*/
pragma solidity 0.7.6;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to !contains(map, key)
if (keyIndex == 0) {
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to contains(map, key)
if (keyIndex != 0) {
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// AddressToUintMap
struct AddressToUintMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(key)), bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToUintMap storage map, address key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(uint256(key)));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(uint256(key)));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToUintMap storage map, uint256 index)
internal
view
returns (address, uint256)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint256(key)), uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key)
internal
view
returns (uint256)
{
return uint256(_get(map._inner, bytes32(uint256(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(
AddressToUintMap storage map,
address key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(key)), errorMessage));
}
}
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity 0.7.6;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./LPRewardsData.sol";
import "../../libraries/EnumerableMap.sol";
import "../interfaces/ILPRewards.sol";
import "../interfaces/IValuePerToken.sol";
import "../../tokens/interfaces/IWETH.sol";
import "../../access/OwnableUpgradeable.sol";
contract LPRewards is
Initializable,
ContextUpgradeable,
OwnableUpgradeable,
PausableUpgradeable,
LPRewardsData,
ILPRewards
{
using Address for address payable;
using EnumerableMap for EnumerableMap.AddressToUintMap;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/* Immutable Internal State */
uint256 internal constant _MULTIPLIER = 1e36;
/* Constructor */
constructor(address owner_) {
init(owner_);
}
/* Initializers */
function init(address owner_) public virtual initializer {
__Context_init_unchained();
__Ownable_init_unchained(owner_);
__Pausable_init_unchained();
}
/* Fallbacks */
receive() external payable {
// Only accept ETH via fallback from the WETH contract
require(msg.sender == _rewardsToken);
}
/* Modifiers */
modifier supportsToken(address token) {
require(supportsStakingToken(token), "LPRewards: unsupported token");
_;
}
/* Public Views */
function accruedRewardsPerTokenFor(address token)
public
view
virtual
override
returns (uint256)
{
return _tokenData[token].arpt;
}
function accruedRewardsPerTokenLastFor(address account, address token)
public
view
virtual
override
returns (uint256)
{
return _users[account].rewardsFor[token].arptLast;
}
function lastRewardsBalanceOf(address account)
public
view
virtual
override
returns (uint256 total)
{
UserData storage user = _users[account];
EnumerableSet.AddressSet storage tokens = user.tokensWithRewards;
for (uint256 i = 0; i < tokens.length(); i++) {
total += user.rewardsFor[tokens.at(i)].pending;
}
}
function lastRewardsBalanceOfFor(address account, address token)
public
view
virtual
override
returns (uint256)
{
return _users[account].rewardsFor[token].pending;
}
function lastTotalRewardsAccrued()
external
view
virtual
override
returns (uint256)
{
return _lastTotalRewardsAccrued;
}
function lastTotalRewardsAccruedFor(address token)
external
view
virtual
override
returns (uint256)
{
return _tokenData[token].lastRewardsAccrued;
}
function numStakingTokens()
external
view
virtual
override
returns (uint256)
{
return _tokens.length();
}
function rewardsBalanceOf(address account)
external
view
virtual
override
returns (uint256)
{
return lastRewardsBalanceOf(account) + _allPendingRewardsFor(account);
}
function rewardsBalanceOfFor(address account, address token)
external
view
virtual
override
returns (uint256)
{
uint256 rewards = lastRewardsBalanceOfFor(account, token);
uint256 amountStaked = stakedBalanceOf(account, token);
if (amountStaked != 0) {
rewards += _pendingRewardsFor(account, token, amountStaked);
}
return rewards;
}
function rewardsForToken(address token)
external
view
virtual
override
returns (uint256)
{
return _tokenData[token].rewards;
}
function rewardsToken() public view virtual override returns (address) {
return _rewardsToken;
}
function sharesFor(address account, address token)
external
view
virtual
override
returns (uint256)
{
return _shares(token, stakedBalanceOf(account, token));
}
function sharesPerToken(address token)
external
view
virtual
override
returns (uint256)
{
return _shares(token, 1e18);
}
function stakedBalanceOf(address account, address token)
public
view
virtual
override
returns (uint256)
{
EnumerableMap.AddressToUintMap storage staked = _users[account].staked;
if (staked.contains(token)) {
return staked.get(token);
}
return 0;
}
function stakingTokenAt(uint256 index)
external
view
virtual
override
returns (address)
{
return _tokens.at(index);
}
function supportsStakingToken(address token)
public
view
virtual
override
returns (bool)
{
return _tokens.contains(token);
}
function totalRewardsAccrued()
public
view
virtual
override
returns (uint256)
{
// Overflow is OK
return _currentRewardsBalance() + _totalRewardsRedeemed;
}
function totalRewardsAccruedFor(address token)
public
view
virtual
override
returns (uint256)
{
TokenData storage td = _tokenData[token];
// Overflow is OK
return td.rewards + td.rewardsRedeemed;
}
function totalRewardsRedeemed()
external
view
virtual
override
returns (uint256)
{
return _totalRewardsRedeemed;
}
function totalRewardsRedeemedFor(address token)
external
view
virtual
override
returns (uint256)
{
return _tokenData[token].rewardsRedeemed;
}
function totalShares()
external
view
virtual
override
returns (uint256 total)
{
for (uint256 i = 0; i < _tokens.length(); i++) {
total = total.add(_totalSharesForToken(_tokens.at(i)));
}
}
function totalSharesFor(address account)
external
view
virtual
override
returns (uint256 total)
{
EnumerableMap.AddressToUintMap storage staked = _users[account].staked;
for (uint256 i = 0; i < staked.length(); i++) {
(address token, uint256 amount) = staked.at(i);
total = total.add(_shares(token, amount));
}
}
function totalSharesForToken(address token)
external
view
virtual
override
returns (uint256)
{
return _totalSharesForToken(token);
}
function totalStaked(address token)
public
view
virtual
override
returns (uint256)
{
return _tokenData[token].totalStaked;
}
function unredeemableRewards()
external
view
virtual
override
returns (uint256)
{
return _unredeemableRewards;
}
function valuePerTokenImpl(address token)
public
view
virtual
override
returns (address)
{
return _tokenData[token].valueImpl;
}
/* Public Mutators */
function addToken(address token, address tokenValueImpl)
external
virtual
override
onlyOwner
{
require(!supportsStakingToken(token), "LPRewards: token already added");
require(
tokenValueImpl != address(0),
"LPRewards: tokenValueImpl cannot be zero address"
);
_tokens.add(token);
// Only update implementation in case this was previously used and removed
_tokenData[token].valueImpl = tokenValueImpl;
emit TokenAdded(_msgSender(), token, tokenValueImpl);
}
function changeTokenValueImpl(address token, address tokenValueImpl)
external
virtual
override
onlyOwner
supportsToken(token)
{
require(
tokenValueImpl != address(0),
"LPRewards: tokenValueImpl cannot be zero address"
);
_tokenData[token].valueImpl = tokenValueImpl;
emit TokenValueImplChanged(_msgSender(), token, tokenValueImpl);
}
function exit(bool asWETH) external virtual override {
unstakeAll();
redeemAllRewards(asWETH);
}
function exitFrom(address token, bool asWETH) external virtual override {
unstakeAllFrom(token);
redeemAllRewardsFrom(token, asWETH);
}
function pause() external virtual override onlyOwner {
_pause();
}
function recoverUnredeemableRewards(address to, uint256 amount)
external
virtual
override
onlyOwner
{
require(
amount <= _unredeemableRewards,
"LPRewards: recovery amount > unredeemable"
);
_unredeemableRewards -= amount;
IERC20(_rewardsToken).safeTransfer(to, amount);
emit RecoveredUnredeemableRewards(_msgSender(), to, amount);
}
function recoverUnstaked(
address token,
address to,
uint256 amount
) external virtual override onlyOwner {
require(token != _rewardsToken, "LPRewards: cannot recover rewardsToken");
uint256 unstaked =
IERC20(token).balanceOf(address(this)).sub(totalStaked(token));
require(amount <= unstaked, "LPRewards: recovery amount > unstaked");
IERC20(token).safeTransfer(to, amount);
emit RecoveredUnstaked(_msgSender(), token, to, amount);
}
function redeemAllRewards(bool asWETH) public virtual override {
address account = _msgSender();
_updateAllRewardsFor(account);
UserData storage user = _users[account];
EnumerableSet.AddressSet storage tokens = user.tokensWithRewards;
uint256 redemption = 0;
for (uint256 length = tokens.length(); length > 0; length--) {
address token = tokens.at(0);
TokenData storage td = _tokenData[token];
UserTokenRewards storage rewards = user.rewardsFor[token];
uint256 pending = rewards.pending; // Save gas
redemption += pending;
rewards.pending = 0;
td.rewards = td.rewards.sub(pending);
td.rewardsRedeemed += pending;
emit RewardPaid(account, token, pending);
tokens.remove(token);
}
_totalRewardsRedeemed += redemption;
_sendRewards(account, redemption, asWETH);
}
function redeemAllRewardsFrom(address token, bool asWETH)
public
virtual
override
{
address account = _msgSender();
_updateRewardFor(account, token);
uint256 pending = _users[account].rewardsFor[token].pending;
if (pending != 0) {
_redeemRewardFrom(token, pending, asWETH);
}
}
function redeemReward(uint256 amount, bool asWETH)
external
virtual
override
{
require(amount != 0, "LPRewards: cannot redeem zero");
address account = _msgSender();
_updateAllRewardsFor(account);
require(
amount <= lastRewardsBalanceOf(account),
"LPRewards: cannot redeem more rewards than earned"
);
UserData storage user = _users[account];
EnumerableSet.AddressSet storage tokens = user.tokensWithRewards;
uint256 amountLeft = amount;
for (uint256 length = tokens.length(); length > 0; length--) {
address token = tokens.at(0);
TokenData storage td = _tokenData[token];
UserTokenRewards storage rewards = user.rewardsFor[token];
uint256 pending = rewards.pending; // Save gas
uint256 taken = 0;
if (pending <= amountLeft) {
taken = pending;
tokens.remove(token);
} else {
taken = amountLeft;
}
rewards.pending = pending - taken;
td.rewards = td.rewards.sub(taken);
td.rewardsRedeemed += taken;
amountLeft -= taken;
emit RewardPaid(account, token, taken);
if (amountLeft == 0) {
break;
}
}
_totalRewardsRedeemed += amount;
_sendRewards(account, amount, asWETH);
}
function redeemRewardFrom(
address token,
uint256 amount,
bool asWETH
) external virtual override {
require(amount != 0, "LPRewards: cannot redeem zero");
address account = _msgSender();
_updateRewardFor(account, token);
require(
amount <= _users[account].rewardsFor[token].pending,
"LPRewards: cannot redeem more rewards than earned"
);
_redeemRewardFrom(token, amount, asWETH);
}
function removeToken(address token)
external
virtual
override
onlyOwner
supportsToken(token)
{
_tokens.remove(token);
// Clean up. Keep totalStaked and rewards since those will be cleaned up by
// users unstaking and redeeming.
_tokenData[token].valueImpl = address(0);
emit TokenRemoved(_msgSender(), token);
}
function setRewardsToken(address token) public virtual override onlyOwner {
_rewardsToken = token;
emit RewardsTokenSet(_msgSender(), token);
}
function stake(address token, uint256 amount)
external
virtual
override
whenNotPaused
supportsToken(token)
{
require(amount != 0, "LPRewards: cannot stake zero");
address account = _msgSender();
_updateRewardFor(account, token);
UserData storage user = _users[account];
TokenData storage td = _tokenData[token];
td.totalStaked += amount;
user.staked.set(token, amount + stakedBalanceOf(account, token));
IERC20(token).safeTransferFrom(account, address(this), amount);
emit Staked(account, token, amount);
}
function unpause() external virtual override onlyOwner {
_unpause();
}
function unstake(address token, uint256 amount) external virtual override {
require(amount != 0, "LPRewards: cannot unstake zero");
address account = _msgSender();
// Prevent making calls to any addresses that were never supported.
uint256 staked = stakedBalanceOf(account, token);
require(
amount <= staked,
"LPRewards: cannot unstake more than staked balance"
);
_unstake(token, amount);
}
function unstakeAll() public virtual override {
UserData storage user = _users[_msgSender()];
for (uint256 length = user.staked.length(); length > 0; length--) {
(address token, uint256 amount) = user.staked.at(0);
_unstake(token, amount);
}
}
function unstakeAllFrom(address token) public virtual override {
_unstake(token, stakedBalanceOf(_msgSender(), token));
}
function updateAccrual() external virtual override {
// Gas savings
uint256 totalRewardsAccrued_ = totalRewardsAccrued();
uint256 pending = totalRewardsAccrued_ - _lastTotalRewardsAccrued;
if (pending == 0) {
return;
}
_lastTotalRewardsAccrued = totalRewardsAccrued_;
// Iterate once to know totalShares
uint256 totalShares_ = 0;
// Store some math for current shares to save on gas and revert ASAP.
uint256[] memory pendingSharesFor = new uint256[](_tokens.length());
for (uint256 i = 0; i < _tokens.length(); i++) {
uint256 share = _totalSharesForToken(_tokens.at(i));
pendingSharesFor[i] = pending.mul(share);
totalShares_ = totalShares_.add(share);
}
if (totalShares_ == 0) {
_unredeemableRewards = _unredeemableRewards.add(pending);
emit AccrualUpdated(_msgSender(), pending);
return;
}
// Iterate twice to allocate rewards to each token.
for (uint256 i = 0; i < _tokens.length(); i++) {
address token = _tokens.at(i);
TokenData storage td = _tokenData[token];
td.rewards += pendingSharesFor[i] / totalShares_;
uint256 rewardsAccrued = totalRewardsAccruedFor(token);
td.arpt = _accruedRewardsPerTokenFor(token, rewardsAccrued);
td.lastRewardsAccrued = rewardsAccrued;
}
emit AccrualUpdated(_msgSender(), pending);
}
function updateReward() external virtual override {
_updateAllRewardsFor(_msgSender());
}
function updateRewardFor(address token) external virtual override {
_updateRewardFor(_msgSender(), token);
}
/* Internal Views */
function _accruedRewardsPerTokenFor(address token, uint256 rewardsAccrued)
internal
view
virtual
returns (uint256)
{
TokenData storage td = _tokenData[token];
// Gas savings
uint256 totalStaked_ = td.totalStaked;
if (totalStaked_ == 0) {
return td.arpt;
}
// Overflow is OK
uint256 delta = rewardsAccrued - td.lastRewardsAccrued;
if (delta == 0) {
return td.arpt;
}
// Use multiplier for better rounding
uint256 rewardsPerToken = delta.mul(_MULTIPLIER) / totalStaked_;
// Overflow is OK
return td.arpt + rewardsPerToken;
}
function _allPendingRewardsFor(address account)
internal
view
virtual
returns (uint256 total)
{
EnumerableMap.AddressToUintMap storage staked = _users[account].staked;
for (uint256 i = 0; i < staked.length(); i++) {
(address token, uint256 amount) = staked.at(i);
total += _pendingRewardsFor(account, token, amount);
}
}
function _currentRewardsBalance() internal view virtual returns (uint256) {
return IERC20(_rewardsToken).balanceOf(address(this));
}
function _pendingRewardsFor(
address account,
address token,
uint256 amountStaked
) internal view virtual returns (uint256) {
uint256 arpt = accruedRewardsPerTokenFor(token);
uint256 arptLast = accruedRewardsPerTokenLastFor(account, token);
// Overflow is OK
uint256 arptDelta = arpt - arptLast;
return amountStaked.mul(arptDelta) / _MULTIPLIER;
}
function _shares(address token, uint256 amountStaked)
internal
view
virtual
returns (uint256)
{
if (!supportsStakingToken(token)) {
return 0;
}
IValuePerToken vptHandle = IValuePerToken(valuePerTokenImpl(token));
(uint256 numerator, uint256 denominator) = vptHandle.valuePerToken();
if (denominator == 0) {
return 0;
}
// Return a 1:1 ratio for value to shares
return amountStaked.mul(numerator) / denominator;
}
function _totalSharesForToken(address token)
internal
view
virtual
returns (uint256)
{
return _shares(token, _tokenData[token].totalStaked);
}
/* Internal Mutators */
function _redeemRewardFrom(
address token,
uint256 amount,
bool asWETH
) internal virtual {
address account = _msgSender();
UserData storage user = _users[account];
UserTokenRewards storage rewards = user.rewardsFor[token];
TokenData storage td = _tokenData[token];
uint256 rewardLeft = rewards.pending - amount;
rewards.pending = rewardLeft;
if (rewardLeft == 0) {
user.tokensWithRewards.remove(token);
}
td.rewards = td.rewards.sub(amount);
td.rewardsRedeemed += amount;
_totalRewardsRedeemed += amount;
_sendRewards(account, amount, asWETH);
emit RewardPaid(account, token, amount);
}
function _sendRewards(
address to,
uint256 amount,
bool asWETH
) internal virtual {
if (asWETH) {
IERC20(_rewardsToken).safeTransfer(to, amount);
} else {
IWETH(_rewardsToken).withdraw(amount);
payable(to).sendValue(amount);
}
}
function _unstake(address token, uint256 amount) internal virtual {
address account = _msgSender();
_updateRewardFor(account, token);
TokenData storage td = _tokenData[token];
td.totalStaked = td.totalStaked.sub(amount);
UserData storage user = _users[account];
EnumerableMap.AddressToUintMap storage staked = user.staked;
uint256 stakeLeft = staked.get(token).sub(amount);
if (stakeLeft == 0) {
staked.remove(token);
user.rewardsFor[token].arptLast = 0;
} else {
staked.set(token, stakeLeft);
}
IERC20(token).safeTransfer(account, amount);
emit Unstaked(account, token, amount);
}
function _updateRewardFor(address account, address token)
internal
virtual
returns (uint256)
{
UserData storage user = _users[account];
UserTokenRewards storage rewards = user.rewardsFor[token];
uint256 total = rewards.pending; // Save gas
uint256 amountStaked = stakedBalanceOf(account, token);
uint256 pending = _pendingRewardsFor(account, token, amountStaked);
if (pending != 0) {
total += pending;
rewards.pending = total;
user.tokensWithRewards.add(token);
}
rewards.arptLast = accruedRewardsPerTokenFor(token);
return total;
}
function _updateAllRewardsFor(address account) internal virtual {
EnumerableMap.AddressToUintMap storage staked = _users[account].staked;
for (uint256 i = 0; i < staked.length(); i++) {
(address token, ) = staked.at(i);
_updateRewardFor(account, token);
}
}
}
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity 0.7.6;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../libraries/EnumerableMap.sol";
abstract contract LPRewardsData {
/* Structs */
struct TokenData {
uint256 arpt;
uint256 lastRewardsAccrued;
uint256 rewards;
uint256 rewardsRedeemed;
uint256 totalStaked;
address valueImpl;
}
struct UserTokenRewards {
uint256 pending;
uint256 arptLast;
}
struct UserData {
EnumerableSet.AddressSet tokensWithRewards;
mapping(address => UserTokenRewards) rewardsFor;
EnumerableMap.AddressToUintMap staked;
}
/* State */
address internal _rewardsToken;
uint256 internal _lastTotalRewardsAccrued;
uint256 internal _totalRewardsRedeemed;
uint256 internal _unredeemableRewards;
EnumerableSet.AddressSet internal _tokens;
mapping(address => TokenData) internal _tokenData;
mapping(address => UserData) internal _users;
uint256[43] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity 0.7.6;
interface ILPRewards {
/* Views */
function accruedRewardsPerTokenFor(address token)
external
view
returns (uint256);
function accruedRewardsPerTokenLastFor(address account, address token)
external
view
returns (uint256);
function lastRewardsBalanceOf(address account)
external
view
returns (uint256);
function lastRewardsBalanceOfFor(address account, address token)
external
view
returns (uint256);
function lastTotalRewardsAccrued() external view returns (uint256);
function lastTotalRewardsAccruedFor(address token)
external
view
returns (uint256);
function numStakingTokens() external view returns (uint256);
function rewardsBalanceOf(address account) external view returns (uint256);
function rewardsBalanceOfFor(address account, address token)
external
view
returns (uint256);
function rewardsForToken(address token) external view returns (uint256);
function rewardsToken() external view returns (address);
function sharesFor(address account, address token)
external
view
returns (uint256);
function sharesPerToken(address token) external view returns (uint256);
function stakedBalanceOf(address account, address token)
external
view
returns (uint256);
function stakingTokenAt(uint256 index) external view returns (address);
function supportsStakingToken(address token) external view returns (bool);
function totalRewardsAccrued() external view returns (uint256);
function totalRewardsAccruedFor(address token)
external
view
returns (uint256);
function totalRewardsRedeemed() external view returns (uint256);
function totalRewardsRedeemedFor(address token)
external
view
returns (uint256);
function totalShares() external view returns (uint256);
function totalSharesFor(address account) external view returns (uint256);
function totalSharesForToken(address token) external view returns (uint256);
function totalStaked(address token) external view returns (uint256);
function unredeemableRewards() external view returns (uint256);
function valuePerTokenImpl(address token) external view returns (address);
/* Mutators */
function addToken(address token, address tokenValueImpl) external;
function changeTokenValueImpl(address token, address tokenValueImpl)
external;
function exit(bool asWETH) external;
function exitFrom(address token, bool asWETH) external;
function pause() external;
function recoverUnredeemableRewards(address to, uint256 amount) external;
function recoverUnstaked(
address token,
address to,
uint256 amount
) external;
function redeemAllRewards(bool asWETH) external;
function redeemAllRewardsFrom(address token, bool asWETH) external;
function redeemReward(uint256 amount, bool asWETH) external;
function redeemRewardFrom(
address token,
uint256 amount,
bool asWETH
) external;
function removeToken(address token) external;
function setRewardsToken(address token) external;
function stake(address token, uint256 amount) external;
function unpause() external;
function unstake(address token, uint256 amount) external;
function unstakeAll() external;
function unstakeAllFrom(address token) external;
function updateAccrual() external;
function updateReward() external;
function updateRewardFor(address token) external;
/* Events */
event AccrualUpdated(address indexed author, uint256 accruedRewards);
event RecoveredUnredeemableRewards(
address indexed author,
address indexed to,
uint256 amount
);
event RecoveredUnstaked(
address indexed author,
address indexed token,
address indexed to,
uint256 amount
);
event RewardPaid(
address indexed account,
address indexed token,
uint256 amount
);
event RewardsTokenSet(address indexed author, address indexed token);
event Staked(address indexed account, address indexed token, uint256 amount);
event TokenAdded(
address indexed author,
address indexed token,
address indexed tokenValueImpl
);
event TokenRemoved(address indexed author, address indexed token);
event TokenValueImplChanged(
address indexed author,
address indexed token,
address indexed tokenValueImpl
);
event Unstaked(
address indexed account,
address indexed token,
uint256 amount
);
}
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity 0.7.6;
interface IValuePerToken {
/* Views */
function token() external view returns (address);
function valuePerToken()
external
view
returns (uint256 numerator, uint256 denominator);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
|
Returns true if the key is in the map. O(1)./
|
function contains(AddressToUintMap storage map, address key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(uint256(key)));
}
| 5,926,031 |
./full_match/1/0xF75D485E9cd0063947e255a214e60bc247fF40f5/sources/convex-platform/contracts/contracts/RewardFactory.sol
|
Create a Managed Reward Pool to handle distribution of all crv mined in a pool/operator = booster(deposit) contract so that new crv can be added and distributedreward manager = this factory so that extra incentive tokens(ex. snx) can be linked to the main managed reward pool
|
function CreateCrvRewards(uint256 _pid, address _depositToken, address _lptoken) external returns (address) {
require(msg.sender == operator, "!auth");
BaseRewardPool4626 rewardPool = new BaseRewardPool4626(_pid,_depositToken,crv,operator, address(this), _lptoken);
emit RewardPoolCreated(address(rewardPool), _pid, _depositToken);
return address(rewardPool);
}
| 4,880,661 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./MemberCard.sol";
contract Vendor is Ownable {
address immutable public memberCard;
constructor(address _memberCard) {
memberCard = _memberCard;
}
event UseMemberCard(address indexed user, uint256 tokenId);
/// @notice useMemberCard user use their card
/// @dev this method can called by anyone
/// @param _tokenId of user's card
function useMemberCard(uint256 _tokenId) external {
MemberCard(memberCard).useToken(_tokenId, _msgSender());
emit UseMemberCard(_msgSender(), _tokenId);
}
}
|
useMemberCard user use their card this method can called by anyone _tokenId of user's card
|
function useMemberCard(uint256 _tokenId) external {
MemberCard(memberCard).useToken(_tokenId, _msgSender());
emit UseMemberCard(_msgSender(), _tokenId);
}
| 13,027,572 |
./full_match/80001/0xCF65E807111c2CC4FCA69818107E3f8DCD570F70/sources/lib/contracts/contracts/smart-wallet/non-upgradeable/Account.sol
|
/// Executes a transaction (called directly from an admin, or by entryPoint)
|
External functions
function execute(
address _target,
uint256 _value,
bytes calldata _calldata
) external virtual onlyAdminOrEntrypoint {
_call(_target, _value, _calldata);
}
| 847,464 |
//Address: 0xaced90c414006b622a4b1ce74fa34b1f650ab319
//Contract name: IndividualityToken
//Balance: 0 Ether
//Verification Date: 1/26/2017
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.0;
library TokenEventLib {
/*
* When underlying solidity issue is fixed this library will not be needed.
* https://github.com/ethereum/solidity/issues/1215
*/
event Transfer(address indexed _from,
address indexed _to);
event Approval(address indexed _owner,
address indexed _spender);
function _Transfer(address _from, address _to) internal {
Transfer(_from, _to);
}
function _Approval(address _owner, address _spender) internal {
Approval(_owner, _spender);
}
}
contract TokenInterface {
/*
* Events
*/
event Mint(address indexed _owner);
event Destroy(address _owner);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event MinterAdded(address who);
event MinterRemoved(address who);
/*
* Minting
*/
/// @dev Mints a new token.
/// @param _owner Address of token owner.
function mint(address _owner) returns (bool success);
/// @dev Destroy a token
/// @param _owner Bytes32 id of the owner of the token
function destroy(address _owner) returns (bool success);
/// @dev Add a new minter
/// @param who Address the address that can now mint tokens.
function addMinter(address who) returns (bool);
/// @dev Remove a minter
/// @param who Address the address that will no longer be a minter.
function removeMinter(address who) returns (bool);
/*
* Read and write storage functions
*/
/// @dev Return the number of tokens
function totalSupply() constant returns (uint supply);
/// @dev Transfers sender token to given address. Returns success.
/// @param _to Address of new token owner.
/// @param _value Bytes32 id of the token to transfer.
function transfer(address _to, uint256 _value) returns (bool success);
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address of token owner.
/// @param _to Address of new token owner.
/// @param _value Bytes32 id of the token to transfer.
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @dev Sets approval spender to transfer ownership of token. Returns success.
/// @param _spender Address of spender..
/// @param _value Bytes32 id of token that can be spend.
function approve(address _spender, uint256 _value) returns (bool success);
/*
* Read storage functions
*/
/// @dev Returns id of token owned by given address (encoded as an integer).
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256 balance);
/// @dev Returns the token id that may transfer from _owner account by _spender..
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
/*
* Extra non ERC20 functions
*/
/// @dev Returns whether the address owns a token.
/// @param _owner Address to check.
function isTokenOwner(address _owner) constant returns (bool);
}
contract IndividualityTokenInterface {
/*
* Read storage functions
*/
/// @dev Returns id of token owned by given address (encoded as an integer).
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256 balance);
/// @dev Returns the token id that may transfer from _owner account by _spender..
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
/*
* Write storage functions
*/
/// @dev Transfers sender token to given address. Returns success.
/// @param _to Address of new token owner.
/// @param _value Bytes32 id of the token to transfer.
function transfer(address _to, uint256 _value) public returns (bool success);
function transfer(address _to) public returns (bool success);
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address of token owner.
/// @param _to Address of new token owner.
/// @param _value Bytes32 id of the token to transfer.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to) public returns (bool success);
/// @dev Sets approval spender to transfer ownership of token. Returns success.
/// @param _spender Address of spender..
/// @param _value Bytes32 id of token that can be spend.
function approve(address _spender, uint256 _value) public returns (bool success);
function approve(address _spender) public returns (bool success);
/*
* Extra non ERC20 functions
*/
/// @dev Returns whether the address owns a token.
/// @param _owner Address to check.
function isTokenOwner(address _owner) constant returns (bool);
}
contract IndividualityToken is TokenInterface, IndividualityTokenInterface {
function IndividualityToken() {
minters[msg.sender] = true;
MinterAdded(msg.sender);
}
modifier minterOnly {
if(!minters[msg.sender]) throw;
_;
}
// address => canmint
mapping (address => bool) minters;
// owner => balance
mapping (address => uint) balances;
// owner => spender => balance
mapping (address => mapping (address => uint)) approvals;
uint numTokens;
/// @dev Mints a new token.
/// @param _to Address of token owner.
function mint(address _to) minterOnly returns (bool success) {
// ensure that the token owner doesn't already own a token.
if (balances[_to] != 0x0) return false;
balances[_to] = 1;
// log the minting of this token.
Mint(_to);
Transfer(0x0, _to, 1);
TokenEventLib._Transfer(0x0, _to);
// increase the supply.
numTokens += 1;
return true;
}
// @dev Mint many new tokens
function mint(address[] _to) minterOnly returns (bool success) {
for(uint i = 0; i < _to.length; i++) {
if(balances[_to[i]] != 0x0) return false;
balances[_to[i]] = 1;
Mint(_to[i]);
Transfer(0x0, _to[i], 1);
TokenEventLib._Transfer(0x0, _to[i]);
}
numTokens += _to.length;
return true;
}
/// @dev Destroy a token
/// @param _owner address owner of the token to destroy
function destroy(address _owner) minterOnly returns (bool success) {
if(balances[_owner] != 1) throw;
balances[_owner] = 0;
numTokens -= 1;
Destroy(_owner);
return true;
}
/// @dev Add a new minter
/// @param who Address the address that can now mint tokens.
function addMinter(address who) minterOnly returns (bool) {
minters[who] = true;
MinterAdded(who);
}
/// @dev Remove a minter
/// @param who Address the address that will no longer be a minter.
function removeMinter(address who) minterOnly returns (bool) {
minters[who] = false;
MinterRemoved(who);
}
/// @dev Return the number of tokens
function totalSupply() constant returns (uint supply) {
return numTokens;
}
/// @dev Returns id of token owned by given address (encoded as an integer).
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256 balance) {
if (_owner == 0x0) {
return 0;
} else {
return balances[_owner];
}
}
/// @dev Returns the token id that may transfer from _owner account by _spender..
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner,
address _spender) constant returns (uint256 remaining) {
return approvals[_owner][_spender];
}
/// @dev Transfers sender token to given address. Returns success.
/// @param _to Address of new token owner.
/// @param _value Bytes32 id of the token to transfer.
function transfer(address _to,
uint256 _value) public returns (bool success) {
if (_value != 1) {
// 1 is the only value that makes any sense here.
return false;
} else if (_to == 0x0) {
// cannot transfer to the null address.
return false;
} else if (balances[msg.sender] == 0x0) {
// msg.sender is not a token owner
return false;
} else if (balances[_to] != 0x0) {
// cannot transfer to an address that already owns a token.
return false;
}
balances[msg.sender] = 0;
balances[_to] = 1;
Transfer(msg.sender, _to, 1);
TokenEventLib._Transfer(msg.sender, _to);
return true;
}
/// @dev Transfers sender token to given address. Returns success.
/// @param _to Address of new token owner.
function transfer(address _to) public returns (bool success) {
return transfer(_to, 1);
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address of token owner.
/// @param _to Address of new token owner.
/// @param _value Bytes32 id of the token to transfer.
function transferFrom(address _from,
address _to,
uint256 _value) public returns (bool success) {
if (_value != 1) {
// Cannot transfer anything other than 1 token.
return false;
} else if (_to == 0x0) {
// Cannot transfer to the null address
return false;
} else if (balances[_from] == 0x0) {
// Cannot transfer if _from is not a token owner
return false;
} else if (balances[_to] != 0x0) {
// Cannot transfer to an existing token owner
return false;
} else if (approvals[_from][msg.sender] == 0) {
// The approved token doesn't match the token being transferred.
return false;
}
// null out the approval
approvals[_from][msg.sender] = 0x0;
// remove the token from the sender.
balances[_from] = 0;
// assign the token to the new owner
balances[_to] = 1;
// log the transfer
Transfer(_from, _to, 1);
TokenEventLib._Transfer(_from, _to);
return true;
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address of token owner.
/// @param _to Address of new token owner.
function transferFrom(address _from, address _to) public returns (bool success) {
return transferFrom(_from, _to, 1);
}
/// @dev Sets approval spender to transfer ownership of token. Returns success.
/// @param _spender Address of spender..
/// @param _value Bytes32 id of token that can be spend.
function approve(address _spender,
uint256 _value) public returns (bool success) {
if (_value != 1) {
// cannot approve any value other than 1
return false;
} else if (_spender == 0x0) {
// cannot approve the null address as a spender.
return false;
} else if (balances[msg.sender] == 0x0) {
// cannot approve if not a token owner.
return false;
}
approvals[msg.sender][_spender] = 1;
Approval(msg.sender, _spender, 1);
TokenEventLib._Approval(msg.sender, _spender);
return true;
}
/// @dev Sets approval spender to transfer ownership of token. Returns success.
/// @param _spender Address of spender..
function approve(address _spender) public returns (bool success) {
return approve(_spender, 1);
}
/*
* Extra non ERC20 functions
*/
/// @dev Returns whether the address owns a token.
/// @param _owner Address to check.
function isTokenOwner(address _owner) constant returns (bool) {
return balances[_owner] != 0;
}
}
|
Transfers sender token to given address. Returns success. _to Address of new token owner.
|
function transfer(address _to) public returns (bool success) {
return transfer(_to, 1);
}
| 5,545,228 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
interface IUniswap {
// To convert DAI to ETH
function SWAPEXACTTOKENSFORETH436(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); //inject NONSTANDARD NAMING
// To convert ETH to YELD and burn it
function SWAPEXACTETHFORTOKENS487(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IERC20 {
function TOTALSUPPLY323() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF269(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE471(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE639(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM45(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER853(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL183(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER264() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA366() 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 Ownable is Context {
address payable private _owner;
event OWNERSHIPTRANSFERRED175(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER264();
emit OWNERSHIPTRANSFERRED175(address(0), _owner);
}
function OWNER564() public view returns (address payable) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER780() { //inject NONSTANDARD NAMING
require(ISOWNER198(), "Ownable: caller is not the owner");
_;
}
function ISOWNER198() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER264() == _owner;
}
function RENOUNCEOWNERSHIP104() public ONLYOWNER780 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED175(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP788(address payable newOwner) public ONLYOWNER780 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP70(newOwner);
}
function _TRANSFEROWNERSHIP70(address payable newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED175(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
function TOTALSUPPLY323() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF269(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER6(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER918(_MSGSENDER264(), recipient, amount);
return true;
}
function ALLOWANCE471(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE639(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, amount);
return true;
}
function TRANSFERFROM45(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER918(sender, recipient, amount);
_APPROVE444(sender, _MSGSENDER264(), _allowances[sender][_MSGSENDER264()].SUB46(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE61(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, _allowances[_MSGSENDER264()][spender].ADD992(addedValue));
return true;
}
function DECREASEALLOWANCE74(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, _allowances[_MSGSENDER264()][spender].SUB46(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER918(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].SUB46(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD992(amount);
emit TRANSFER853(sender, recipient, amount);
}
function _MINT980(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD992(amount);
_balances[account] = _balances[account].ADD992(amount);
emit TRANSFER853(address(0), account, amount);
}
function _BURN375(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB46(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB46(amount);
emit TRANSFER853(account, address(0), amount);
}
function _APPROVE444(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 APPROVAL183(owner, spender, amount);
}
function _BURNFROM405(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN375(account, amount);
_APPROVE444(account, _MSGSENDER264(), _allowances[account][_MSGSENDER264()].SUB46(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME61() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL851() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS917() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier NONREENTRANT890() { //inject NONSTANDARD NAMING
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
library SafeMath {
function ADD992(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB46(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB46(a, b, "SafeMath: subtraction overflow");
}
function SUB46(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 MUL613(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 DIV312(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV312(a, b, "SafeMath: division by zero");
}
function DIV312(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 MOD928(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD928(a, b, "SafeMath: modulo by zero");
}
function MOD928(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT42(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 TOPAYABLE515(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE559(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 SAFETRANSFER60(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.TRANSFER6.selector, to, value));
}
function SAFETRANSFERFROM510(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.TRANSFERFROM45.selector, from, to, value));
}
function SAFEAPPROVE585(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE471(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, value));
}
function SAFEINCREASEALLOWANCE437(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE471(address(this), spender).ADD992(value);
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE12(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE471(address(this), spender).SUB46(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN106(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT42(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Compound {
function MINT570 ( uint256 mintAmount ) external returns ( uint256 ); //inject NONSTANDARD NAMING
function REDEEM919(uint256 redeemTokens) external returns (uint256); //inject NONSTANDARD NAMING
function EXCHANGERATESTORED297() external view returns (uint); //inject NONSTANDARD NAMING
}
interface Fulcrum {
function MINT570(address receiver, uint256 amount) external payable returns (uint256 mintAmount); //inject NONSTANDARD NAMING
function BURN957(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); //inject NONSTANDARD NAMING
function ASSETBALANCEOF748(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
}
interface ILendingPoolAddressesProvider {
function GETLENDINGPOOL795() external view returns (address); //inject NONSTANDARD NAMING
}
interface Aave {
function DEPOSIT261(address _reserve, uint256 _amount, uint16 _referralCode) external; //inject NONSTANDARD NAMING
}
interface AToken {
function REDEEM919(uint256 amount) external; //inject NONSTANDARD NAMING
}
interface IIEarnManager {
function RECOMMEND876(address _token) external view returns ( //inject NONSTANDARD NAMING
string memory choice,
uint256 capr,
uint256 iapr,
uint256 aapr,
uint256 dapr
);
}
contract Structs {
struct Val {
uint256 value;
}
enum ActionType {
Deposit, // supply tokens
Withdraw // borrow tokens
}
enum AssetDenomination {
Wei // the amount is denominated in wei
}
enum AssetReference {
Delta // the amount is given as a delta from the current value
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
contract DyDx is Structs {
function GETACCOUNTWEI173(Info memory account, uint256 marketId) public view returns (Wei memory); //inject NONSTANDARD NAMING
function OPERATE410(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING
}
interface LendingPoolAddressesProvider {
function GETLENDINGPOOL795() external view returns (address); //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE176() external view returns (address); //inject NONSTANDARD NAMING
}
contract yTUSD is ERC20, ERC20Detailed, ReentrancyGuard, Structs, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
uint256 public pool;
address public token;
address public compound;
address public fulcrum;
address public aave;
address public aavePool;
address public aaveToken;
address public dydx;
uint256 public dToken;
address public apr;
address public chai;
// Add other tokens if implemented for another stablecoin
address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public tusd = 0x0000000000085d4780B73119b644AE5ecd22b376;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public retirementYeldTreasury;
IERC20 public yeldToken;
uint256 public maximumTokensToBurn = 50000 * 1e18;
// When you stake say 1000 TUSD for a day that will be your maximum
// if you stake the next time 300 TUSD your maximum will stay the same
// if you stake 2000 at once it will increase to 2000 TUSD
mapping(bytes32 => uint256) public numberOfParticipants;
mapping(address => uint256) public depositBlockStarts;
uint256 public constant onedayinblocks32 = 6500; //inject NONSTANDARD NAMING
uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility
uint256 public constant onemillion240 = 1e6; //inject NONSTANDARD NAMING
enum Lender {
NONE,
DYDX,
COMPOUND,
AAVE,
FULCRUM
}
Lender public provider = Lender.NONE;
constructor (address _yeldToken, address payable _retirementYeldTreasury) public payable ERC20Detailed("yearn TUSD", "yTUSD", 18) {
token = address(0x0000000000085d4780B73119b644AE5ecd22b376);
apr = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8);
dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
aavePool = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3);
fulcrum = address(0x493C57C4763932315A328269E1ADaD09653B9081);
aaveToken = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
compound = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
chai = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
dToken = 3;
yeldToken = IERC20(_yeldToken);
retirementYeldTreasury = _retirementYeldTreasury;
APPROVETOKEN94();
}
// To receive ETH after converting it from TUSD
function () external payable {}
function SETRETIREMENTYELDTREASURY648(address payable _treasury) public ONLYOWNER780 { //inject NONSTANDARD NAMING
retirementYeldTreasury = _treasury;
}
// In case a new uniswap router version is released
function SETUNISWAPROUTER36(address _uniswapRouter) public ONLYOWNER780 { //inject NONSTANDARD NAMING
uniswapRouter = _uniswapRouter;
}
function EXTRACTTOKENSIFSTUCK789(address _token, uint256 _amount) public ONLYOWNER780 { //inject NONSTANDARD NAMING
IERC20(_token).TRANSFER6(msg.sender, _amount);
}
function EXTRACTETHIFSTUCK584() public ONLYOWNER780 { //inject NONSTANDARD NAMING
OWNER564().transfer(address(this).balance);
}
function CHANGEYELDTOREWARDPERDAY778(uint256 _amount) public ONLYOWNER780 { //inject NONSTANDARD NAMING
yeldToRewardPerDay = _amount;
}
function GETGENERATEDYELDS438() public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 blocksPassed;
if (depositBlockStarts[msg.sender] > 0) {
blocksPassed = block.number.SUB46(depositBlockStarts[msg.sender]);
} else {
blocksPassed = 0;
}
// This will work because amount is a token with 18 decimals
// Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1
// That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day
// your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since
// we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding
// For USDC and Tether gotta multiply by 1e12 since they have 6 decimals to get the proper result of YELD
uint256 ibalance = BALANCEOF269(msg.sender); // Balance of yTokens
uint256 accomulatedStablecoins = (CALCPOOLVALUEINTOKEN983().MUL613(ibalance)).DIV312(_totalSupply);
uint256 generatedYelds = accomulatedStablecoins.DIV312(onemillion240).MUL613(yeldToRewardPerDay.DIV312(1e18)).MUL613(blocksPassed).DIV312(onedayinblocks32);
return generatedYelds;
}
function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT225() public { //inject NONSTANDARD NAMING
uint256 ibalance = BALANCEOF269(msg.sender);
uint256 accomulatedStablecoins = (CALCPOOLVALUEINTOKEN983().MUL613(ibalance)).DIV312(_totalSupply);
require(depositBlockStarts[msg.sender] > 0 && accomulatedStablecoins > 0, 'Must have deposited stablecoins beforehand');
uint256 generatedYelds = GETGENERATEDYELDS438();
depositBlockStarts[msg.sender] = block.number;
yeldToken.TRANSFER6(msg.sender, generatedYelds);
}
function DEPOSIT261(uint256 _amount) //inject NONSTANDARD NAMING
external
NONREENTRANT890
{
require(_amount > 0, "deposit must be greater than 0");
pool = CALCPOOLVALUEINTOKEN983();
IERC20(token).SAFETRANSFERFROM510(msg.sender, address(this), _amount);
// Yeld
if (GETGENERATEDYELDS438() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT225();
depositBlockStarts[msg.sender] = block.number;
// Yeld
// Calculate pool shares
uint256 shares = 0;
if (pool == 0) {
shares = _amount;
pool = _amount;
} else {
shares = (_amount.MUL613(_totalSupply)).DIV312(pool);
}
pool = CALCPOOLVALUEINTOKEN983();
_MINT980(msg.sender, shares);
REBALANCE90();
}
// Converts TUSD to ETH and returns how much ETH has been received from Uniswap
function TUSDTOETH442(uint256 _amount) internal returns(uint256) { //inject NONSTANDARD NAMING
IERC20(tusd).SAFEAPPROVE585(uniswapRouter, 0);
IERC20(tusd).SAFEAPPROVE585(uniswapRouter, _amount);
address[] memory path = new address[](2);
path[0] = tusd;
path[1] = weth;
// swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
// 'amounts' is an array where [0] is input TUSD amount and [1] is the resulting ETH after the conversion
// even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap
// https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
uint[] memory amounts = IUniswap(uniswapRouter).SWAPEXACTTOKENSFORETH436(_amount, uint(0), path, address(this), now.ADD992(1800));
return amounts[1];
}
// Buys YELD tokens paying in ETH on Uniswap and removes them from circulation
// Returns how many YELD tokens have been burned
function BUYNBURN597(uint256 _ethToSwap) internal returns(uint256) { //inject NONSTANDARD NAMING
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(yeldToken);
// Burns the tokens by taking them out of circulation, sending them to the 0x0 address
uint[] memory amounts = IUniswap(uniswapRouter).SWAPEXACTETHFORTOKENS487.value(_ethToSwap)(uint(0), path, address(0), now.ADD992(1800));
return amounts[1];
}
// No rebalance implementation for lower fees and faster swaps
function WITHDRAW331(uint256 _shares) //inject NONSTANDARD NAMING
external
NONREENTRANT890
{
require(_shares > 0, "withdraw must be greater than 0");
uint256 ibalance = BALANCEOF269(msg.sender);
require(_shares <= ibalance, "insufficient balance");
pool = CALCPOOLVALUEINTOKEN983();
uint256 stablecoinsToWithdraw = (pool.MUL613(_shares)).DIV312(_totalSupply);
_balances[msg.sender] = _balances[msg.sender].SUB46(_shares, "redeem amount exceeds balance");
_totalSupply = _totalSupply.SUB46(_shares);
emit TRANSFER853(msg.sender, address(0), _shares);
uint256 b = IERC20(token).BALANCEOF269(address(this));
if (b < stablecoinsToWithdraw) {
_WITHDRAWSOME967(stablecoinsToWithdraw.SUB46(b));
}
// Yeld
uint256 generatedYelds = GETGENERATEDYELDS438();
// Take 1% of the amount to withdraw
uint256 onePercent = stablecoinsToWithdraw.DIV312(100);
depositBlockStarts[msg.sender] = block.number;
yeldToken.TRANSFER6(msg.sender, generatedYelds);
// Take a portion of the profits for the buy and burn and retirement yeld
// Convert half the TUSD earned into ETH for the protocol algorithms
uint256 stakingProfits = TUSDTOETH442(onePercent);
uint256 tokensAlreadyBurned = yeldToken.BALANCEOF269(address(0));
if (tokensAlreadyBurned < maximumTokensToBurn) {
// 98% is the 49% doubled since we already took the 50%
uint256 ethToSwap = stakingProfits.MUL613(98).DIV312(100);
// Buy and burn only applies up to 50k tokens burned
BUYNBURN597(ethToSwap);
// 1% for the Retirement Yield
uint256 retirementYeld = stakingProfits.MUL613(2).DIV312(100);
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
} else {
// If we've reached the maximum burn point, send half the profits to the treasury to reward holders
uint256 retirementYeld = stakingProfits;
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
}
IERC20(token).SAFETRANSFER60(msg.sender, stablecoinsToWithdraw.SUB46(onePercent));
// Yeld
pool = CALCPOOLVALUEINTOKEN983();
REBALANCE90();
}
function RECOMMEND876() public view returns (Lender) { //inject NONSTANDARD NAMING
(,uint256 capr,uint256 iapr,uint256 aapr,uint256 dapr) = IIEarnManager(apr).RECOMMEND876(token);
uint256 max = 0;
if (capr > max) {
max = capr;
}
if (iapr > max) {
max = iapr;
}
if (aapr > max) {
max = aapr;
}
if (dapr > max) {
max = dapr;
}
Lender newProvider = Lender.NONE;
if (max == capr) {
newProvider = Lender.COMPOUND;
} else if (max == iapr) {
newProvider = Lender.FULCRUM;
} else if (max == aapr) {
newProvider = Lender.AAVE;
} else if (max == dapr) {
newProvider = Lender.DYDX;
}
return newProvider;
}
function GETAAVE657() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave).GETLENDINGPOOL795();
}
function GETAAVECORE248() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave).GETLENDINGPOOLCORE176();
}
function APPROVETOKEN94() public { //inject NONSTANDARD NAMING
IERC20(token).SAFEAPPROVE585(compound, uint(-1));
IERC20(token).SAFEAPPROVE585(dydx, uint(-1));
IERC20(token).SAFEAPPROVE585(GETAAVECORE248(), uint(-1));
IERC20(token).SAFEAPPROVE585(fulcrum, uint(-1));
}
function BALANCE782() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(address(this));
}
function BALANCEDYDXAVAILABLE330() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(dydx);
}
function BALANCEDYDX86() public view returns (uint256) { //inject NONSTANDARD NAMING
Wei memory bal = DyDx(dydx).GETACCOUNTWEI173(Info(address(this), 0), dToken);
return bal.value;
}
function BALANCECOMPOUND355() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(compound).BALANCEOF269(address(this));
}
function BALANCECOMPOUNDINTOKEN294() public view returns (uint256) { //inject NONSTANDARD NAMING
// Mantisa 1e18 to decimals
uint256 b = BALANCECOMPOUND355();
if (b > 0) {
b = b.MUL613(Compound(compound).EXCHANGERATESTORED297()).DIV312(1e18);
}
return b;
}
function BALANCEFULCRUMAVAILABLE395() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(chai).BALANCEOF269(fulcrum);
}
function BALANCEFULCRUMINTOKEN503() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 b = BALANCEFULCRUM271();
if (b > 0) {
b = Fulcrum(fulcrum).ASSETBALANCEOF748(address(this));
}
return b;
}
function BALANCEFULCRUM271() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(fulcrum).BALANCEOF269(address(this));
}
function BALANCEAAVEAVAILABLE892() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(aavePool);
}
function BALANCEAAVE873() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(aaveToken).BALANCEOF269(address(this));
}
function REBALANCE90() public { //inject NONSTANDARD NAMING
Lender newProvider = RECOMMEND876();
if (newProvider != provider) {
_WITHDRAWALL499();
}
if (BALANCE782() > 0) {
if (newProvider == Lender.DYDX) {
_SUPPLYDYDX870(BALANCE782());
} else if (newProvider == Lender.FULCRUM) {
_SUPPLYFULCRUM37(BALANCE782());
} else if (newProvider == Lender.COMPOUND) {
_SUPPLYCOMPOUND942(BALANCE782());
} else if (newProvider == Lender.AAVE) {
_SUPPLYAAVE258(BALANCE782());
}
}
provider = newProvider;
}
function _WITHDRAWALL499() internal { //inject NONSTANDARD NAMING
uint256 amount = BALANCECOMPOUND355();
if (amount > 0) {
_WITHDRAWSOMECOMPOUND259(BALANCECOMPOUNDINTOKEN294().SUB46(1));
}
amount = BALANCEDYDX86();
if (amount > 0) {
if (amount > BALANCEDYDXAVAILABLE330()) {
amount = BALANCEDYDXAVAILABLE330();
}
_WITHDRAWDYDX942(amount);
}
amount = BALANCEFULCRUM271();
if (amount > 0) {
if (amount > BALANCEFULCRUMAVAILABLE395().SUB46(1)) {
amount = BALANCEFULCRUMAVAILABLE395().SUB46(1);
}
_WITHDRAWSOMEFULCRUM209(amount);
}
amount = BALANCEAAVE873();
if (amount > 0) {
if (amount > BALANCEAAVEAVAILABLE892()) {
amount = BALANCEAAVEAVAILABLE892();
}
_WITHDRAWAAVE427(amount);
}
}
function _WITHDRAWSOMECOMPOUND259(uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 b = BALANCECOMPOUND355();
uint256 bT = BALANCECOMPOUNDINTOKEN294();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.MUL613(_amount)).DIV312(bT).ADD992(1);
_WITHDRAWCOMPOUND330(amount);
}
function _WITHDRAWSOMEFULCRUM209(uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 b = BALANCEFULCRUM271();
uint256 bT = BALANCEFULCRUMINTOKEN503();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.MUL613(_amount)).DIV312(bT).ADD992(1);
_WITHDRAWFULCRUM371(amount);
}
function _WITHDRAWSOME967(uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
uint256 origAmount = _amount;
uint256 amount = BALANCECOMPOUND355();
if (amount > 0) {
if (_amount > BALANCECOMPOUNDINTOKEN294().SUB46(1)) {
_WITHDRAWSOMECOMPOUND259(BALANCECOMPOUNDINTOKEN294().SUB46(1));
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWSOMECOMPOUND259(_amount);
return true;
}
}
amount = BALANCEDYDX86();
if (amount > 0) {
if (_amount > BALANCEDYDXAVAILABLE330()) {
_WITHDRAWDYDX942(BALANCEDYDXAVAILABLE330());
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWDYDX942(_amount);
return true;
}
}
amount = BALANCEFULCRUM271();
if (amount > 0) {
if (_amount > BALANCEFULCRUMAVAILABLE395().SUB46(1)) {
amount = BALANCEFULCRUMAVAILABLE395().SUB46(1);
_WITHDRAWSOMEFULCRUM209(BALANCEFULCRUMAVAILABLE395().SUB46(1));
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWSOMEFULCRUM209(amount);
return true;
}
}
amount = BALANCEAAVE873();
if (amount > 0) {
if (_amount > BALANCEAAVEAVAILABLE892()) {
_WITHDRAWAAVE427(BALANCEAAVEAVAILABLE892());
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWAAVE427(_amount);
return true;
}
}
return true;
}
function _SUPPLYDYDX870(uint256 amount) internal { //inject NONSTANDARD NAMING
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Deposit;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).OPERATE410(infos, args);
}
function _SUPPLYAAVE258(uint amount) internal { //inject NONSTANDARD NAMING
Aave(GETAAVE657()).DEPOSIT261(token, amount, 0);
}
function _SUPPLYFULCRUM37(uint amount) internal { //inject NONSTANDARD NAMING
require(Fulcrum(fulcrum).MINT570(address(this), amount) > 0, "FULCRUM: supply failed");
}
function _SUPPLYCOMPOUND942(uint amount) internal { //inject NONSTANDARD NAMING
require(Compound(compound).MINT570(amount) == 0, "COMPOUND: supply failed");
}
function _WITHDRAWAAVE427(uint amount) internal { //inject NONSTANDARD NAMING
AToken(aaveToken).REDEEM919(amount);
}
function _WITHDRAWFULCRUM371(uint amount) internal { //inject NONSTANDARD NAMING
require(Fulcrum(fulcrum).BURN957(address(this), amount) > 0, "FULCRUM: withdraw failed");
}
function _WITHDRAWCOMPOUND330(uint amount) internal { //inject NONSTANDARD NAMING
require(Compound(compound).REDEEM919(amount) == 0, "COMPOUND: withdraw failed");
}
function _WITHDRAWDYDX942(uint256 amount) internal { //inject NONSTANDARD NAMING
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Withdraw;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).OPERATE410(infos, args);
}
function CALCPOOLVALUEINTOKEN983() public view returns (uint) { //inject NONSTANDARD NAMING
return BALANCECOMPOUNDINTOKEN294()
.ADD992(BALANCEFULCRUMINTOKEN503())
.ADD992(BALANCEDYDX86())
.ADD992(BALANCEAAVE873())
.ADD992(BALANCE782());
}
function GETPRICEPERFULLSHARE370() public view returns (uint) { //inject NONSTANDARD NAMING
uint _pool = CALCPOOLVALUEINTOKEN983();
return _pool.MUL613(1e18).DIV312(_totalSupply);
}
}
|
inject NONSTANDARD NAMING
|
function _WITHDRAWSOMECOMPOUND259(uint256 _amount) internal {
| 977,214 |
./full_match/1/0x8610f734cB2001A3Ab7ed7A8A0da898776D99dA9/sources/contracts/utils/AddressArrayLib.sol
|
Helper to remove items from an array. Removes all matching occurrences of each item. Does not assert uniqueness of either array.
|
function removeItems(
address[] memory _self,
address[] memory _itemsToRemove
) internal pure returns (address[] memory nextArray_) {
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
| 2,981,624 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "./interfaces/IERC20Minimal.sol";
import "./libraries/TransferHelper.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IVaultManager.sol";
import "./interfaces/IERC721Minimal.sol";
import "./interfaces/IV1.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IUniswapV2FactoryMinimal.sol";
import "../../tokens/IStablecoin.sol";
contract Vault is IVault {
/// Uniswap v2 factory interface
address public override v2Factory;
/// Address of a manager
address public override manager;
/// Address of debt;
address public override debt;
/// Address of vault ownership registry
address public override v1;
/// Address of a collateral
address public override collateral;
/// Vault global identifier
uint256 public override vaultId;
/// Borrowed amount
uint256 public override borrow;
/// Created block timestamp
uint256 public override createdAt;
/// Address of wrapped eth
address public override WETH;
constructor() public {
manager = msg.sender;
createdAt = block.timestamp;
}
modifier onlyVaultOwner() {
require(
IERC721Minimal(v1).ownerOf(vaultId) == msg.sender,
"Vault: Vault is not owned by you"
);
_;
}
// called once by the factory at time of deployment
function initialize(
uint256 vaultId_,
address collateral_,
address debt_,
address v1_,
uint256 amount_,
address v2Factory_,
address weth_
) external {
require(msg.sender == manager, "Vault: FORBIDDEN"); // sufficient check
vaultId = vaultId_;
collateral = collateral_;
debt = debt_;
v1 = v1_;
borrow = amount_;
v2Factory = v2Factory_;
WETH = weth_;
}
/// liquidate
function liquidate() external override {
require(
!IVaultManager(manager).isValidCDP(
collateral,
debt,
IERC20Minimal(collateral).balanceOf(address(this)),
IERC20Minimal(debt).balanceOf(address(this))
),
"Vault: Position is still safe"
);
// check the pair if it exists
address pair = IUniswapV2FactoryMinimal(v2Factory).getPair(
collateral,
debt
);
require(pair != address(0), "Vault: Liquidating pair not supported");
uint256 balance = IERC20Minimal(collateral).balanceOf(address(this));
uint256 lfr = IVaultManager(manager).getLFR(collateral);
uint256 liquidationFee = (lfr * balance) / 100;
uint256 left = _sendFee(collateral, balance, liquidationFee);
// Distribute collaterals
TransferHelper.safeTransfer(collateral, pair, left);
// burn vault nft
_burnV1FromVault();
emit Liquidated(address(this), collateral, balance);
// self destruct the contract, send remaining balance if collateral is native currency
selfdestruct(payable(msg.sender));
}
/// Deposit collateral
function depositCollateralNative()
external
payable
override
onlyVaultOwner
{
require(collateral == WETH, "Vault: collateral is not a native asset");
// wrap deposit
IWETH(WETH).deposit{value: msg.value}();
emit DepositCollateral(vaultId, msg.value);
}
/// Deposit collateral
function depositCollateral(uint256 amount_)
external
override
onlyVaultOwner
{
TransferHelper.safeTransferFrom(
collateral,
msg.sender,
address(this),
amount_
);
emit DepositCollateral(vaultId, amount_);
}
/// Withdraw collateral as native currency
function withdrawCollateralNative(uint256 amount_)
external
payable
override
onlyVaultOwner
{
require(collateral == WETH, "Vault: collateral is not a native asset");
if (borrow != 0) {
require(
IVaultManager(manager).isValidCDP(
collateral,
debt,
IERC20Minimal(collateral).balanceOf(address(this)) -
amount_,
borrow
),
"Vault: below MCR"
);
}
// unwrap collateral
IWETH(WETH).withdraw(amount_);
// send withdrawn native currency
payable(msg.sender).transfer(address(this).balance);
emit WithdrawCollateral(vaultId, amount_);
}
/// Withdraw collateral
function withdrawCollateral(uint256 amount_)
external
override
onlyVaultOwner
{
require(
IERC20Minimal(collateral).balanceOf(address(this)) >= amount_,
"Vault: Not enough collateral"
);
if (borrow != 0) {
require(
IVaultManager(manager).isValidCDP(
collateral,
debt,
IERC20Minimal(collateral).balanceOf(address(this)) -
amount_,
borrow
),
"Vault: below MCR"
);
}
TransferHelper.safeTransfer(collateral, msg.sender, amount_);
emit WithdrawCollateral(vaultId, amount_);
}
/// Payback MTR
function payDebt(uint256 amount_) external override onlyVaultOwner {
// calculate debt with interest
uint256 fee = _calculateFee();
require(amount_ != 0, "Vault: amount is zero");
// send MTR to the vault
TransferHelper.safeTransferFrom(
debt,
msg.sender,
address(this),
amount_
);
uint256 left = _sendFee(debt, amount_, fee);
_burnMTRFromVault(left);
borrow -= left;
emit PayBack(vaultId, borrow, fee);
}
/// Close CDP
function closeVault(uint256 amount_) external override onlyVaultOwner {
// calculate debt with interest
uint256 fee = _calculateFee();
require(
fee + borrow == amount_,
"Vault: not enough balance to payback"
);
// send MTR to the vault
TransferHelper.safeTransferFrom(
debt,
msg.sender,
address(this),
amount_
);
// send fee to the pool
uint256 left = _sendFee(debt, amount_, fee);
// burn mtr debt with interest
_burnMTRFromVault(left);
// burn vault nft
_burnV1FromVault();
emit CloseVault(address(this), amount_, fee);
// self destruct the contract, send remaining balance if collateral is native currency
selfdestruct(payable(msg.sender));
}
/// burn vault v1
function _burnV1FromVault() internal {
IV1(v1).burnFromVault(vaultId);
}
/// burn vault mtr
function _burnMTRFromVault(uint256 amount_) internal {
IStablecoin(debt).burnFrom(msg.sender, amount_);
}
function _calculateFee() internal returns (uint256) {
uint256 assetValue = IVaultManager(manager).getAssetValue(debt, borrow);
uint256 sfr = IVaultManager(manager).getSFR(collateral);
/// (sfr * assetValue/100) * (duration in months)
uint256 sfrTimesV = sfr * assetValue;
// get duration in months
uint256 duration = (block.timestamp - createdAt) / 60 / 60 / 24 / 30;
require(sfrTimesV >= assetValue); // overflow check
return (sfrTimesV / 100) * duration;
}
function getDebt() external override returns (uint256) {
return _calculateFee() + borrow;
}
function _sendFee(
address asset_,
uint256 amount_,
uint256 fee_
) internal returns (uint256 left) {
address dividend = IVaultManager(manager).dividend();
address feeTo = IVaultManager(manager).feeTo();
address treasury = IVaultManager(manager).treasury();
bool feeOn = feeTo != address(0);
bool treasuryOn = treasury != address(0);
bool dividendOn = dividend != address(0);
// send fee to the pool
if (feeOn) {
if (dividendOn) {
uint256 half = fee_ / 2;
TransferHelper.safeTransfer(asset_, dividend, half);
TransferHelper.safeTransfer(asset_, feeTo, half);
} else if (dividendOn && treasuryOn) {
uint256 third = fee_ / 3;
TransferHelper.safeTransfer(asset_, dividend, third);
TransferHelper.safeTransfer(asset_, feeTo, third);
TransferHelper.safeTransfer(asset_, treasury, third);
} else {
TransferHelper.safeTransfer(asset_, feeTo, fee_);
}
}
return amount_ - fee_;
}
}
|
liquidate check the pair if it exists Distribute collaterals burn vault nft self destruct the contract, send remaining balance if collateral is native currency
|
function liquidate() external override {
require(
!IVaultManager(manager).isValidCDP(
collateral,
debt,
IERC20Minimal(collateral).balanceOf(address(this)),
IERC20Minimal(debt).balanceOf(address(this))
),
"Vault: Position is still safe"
);
address pair = IUniswapV2FactoryMinimal(v2Factory).getPair(
collateral,
debt
);
require(pair != address(0), "Vault: Liquidating pair not supported");
uint256 balance = IERC20Minimal(collateral).balanceOf(address(this));
uint256 lfr = IVaultManager(manager).getLFR(collateral);
uint256 liquidationFee = (lfr * balance) / 100;
uint256 left = _sendFee(collateral, balance, liquidationFee);
TransferHelper.safeTransfer(collateral, pair, left);
_burnV1FromVault();
emit Liquidated(address(this), collateral, balance);
selfdestruct(payable(msg.sender));
}
| 13,069,828 |
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
* @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 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 StandardToken
* @dev https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/StandardToken.sol
* @dev Standard ERC20 token
*/
contract StandardToken {
using SafeMath for uint256;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => uint256) internal balances_;
mapping(address => mapping(address => uint256)) internal allowed_;
uint256 internal totalSupply_;
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances_[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed_ to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed_[_owner][_spender];
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances_[msg.sender]);
balances_[msg.sender] = balances_[msg.sender].sub(_value);
balances_[_to] = balances_[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances_[_from]);
require(_value <= allowed_[_from][msg.sender]);
balances_[_from] = balances_[_from].sub(_value);
balances_[_to] = balances_[_to].add(_value);
allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed_[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
}
/**
* @title EthTeamContract
* @dev The team token. One token represents a team. EthTeamContract is also a ERC20 standard token.
*/
contract EthTeamContract is StandardToken, Ownable {
event Buy(address indexed token, address indexed from, uint256 value, uint256 weiValue);
event Sell(address indexed token, address indexed from, uint256 value, uint256 weiValue);
event BeginGame(address indexed team1, address indexed team2, uint64 gameTime);
event EndGame(address indexed team1, address indexed team2, uint8 gameResult);
event ChangeStatus(address indexed team, uint8 status);
/**
* @dev Token price based on ETH
*/
uint256 public price;
/**
* @dev status=0 buyable & sellable, user can buy or sell the token.
* status=1 not buyable & not sellable, user cannot buy or sell the token.
*/
uint8 public status;
/**
* @dev The game start time. gameTime=0 means game time is not enabled or not started.
*/
uint64 public gameTime;
/**
* @dev If the time is older than FinishTime (usually one month after game).
* The owner has permission to transfer the balance to the feeOwner.
* The user can get back the balance using the website after this time.
*/
uint64 public finishTime;
/**
* @dev The fee owner. The fee will send to this address.
*/
address public feeOwner;
/**
* @dev Game opponent, gameOpponent is also a EthTeamContract.
*/
address public gameOpponent;
/**
* @dev Team name and team symbol will be ERC20 token name and symbol. Token decimals will be 3.
* Token total supply will be 0. The initial price will be 1 szabo (1000000000000 Wei)
*/
function EthTeamContract(
string _teamName, string _teamSymbol, address _gameOpponent, uint64 _gameTime, uint64 _finishTime, address _feeOwner
) public {
name = _teamName;
symbol = _teamSymbol;
decimals = 3;
totalSupply_ = 0;
price = 1 szabo;
gameOpponent = _gameOpponent;
gameTime = _gameTime;
finishTime = _finishTime;
feeOwner = _feeOwner;
owner = msg.sender;
}
/**
* @dev Sell Or Transfer the token.
*
* Override ERC20 transfer token function. If the _to address is not this EthTeamContract,
* then call the super transfer function, which will be ERC20 token transfer.
* Otherwise, the user want to sell the token (EthTeamContract -> ETH).
* @param _to address The address which you want to transfer/sell to
* @param _value uint256 the amount of tokens to be transferred/sold
*/
function transfer(address _to, uint256 _value) public returns (bool) {
if (_to != address(this)) {
return super.transfer(_to, _value);
}
require(_value <= balances_[msg.sender] && status == 0);
// If gameTime is enabled (larger than 1514764800 (2018-01-01))
if (gameTime > 1514764800) {
// We will not allowed to sell after game start
require(gameTime > block.timestamp);
}
balances_[msg.sender] = balances_[msg.sender].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
uint256 weiAmount = price.mul(_value);
msg.sender.transfer(weiAmount);
emit Transfer(msg.sender, _to, _value);
emit Sell(_to, msg.sender, _value, weiAmount);
return true;
}
/**
* @dev Buy token using ETH
* User send ETH to this EthTeamContract, then his token balance will be increased based on price.
* The total supply will also be increased.
*/
function() payable public {
require(status == 0 && price > 0);
// If gameTime is enabled (larger than 1514764800 (2018-01-01))
if (gameTime > 1514764800) {
// We will not allowed to buy after game start
require(gameTime > block.timestamp);
}
uint256 amount = msg.value.div(price);
balances_[msg.sender] = balances_[msg.sender].add(amount);
totalSupply_ = totalSupply_.add(amount);
emit Transfer(address(this), msg.sender, amount);
emit Buy(address(this), msg.sender, amount, msg.value);
}
/**
* @dev The the game status.
*
* status = 0 buyable & sellable, user can buy or sell the token.
* status=1 not buyable & not sellable, user cannot buy or sell the token.
* @param _status The game status.
*/
function changeStatus(uint8 _status) onlyOwner public {
require(status != _status);
status = _status;
emit ChangeStatus(address(this), _status);
}
/**
* @dev Change the fee owner.
*
* @param _feeOwner The new fee owner.
*/
function changeFeeOwner(address _feeOwner) onlyOwner public {
require(_feeOwner != feeOwner && _feeOwner != address(0));
feeOwner = _feeOwner;
}
/**
* @dev Finish the game
*
* If the time is older than FinishTime (usually one month after game).
* The owner has permission to transfer the balance to the feeOwner.
* The user can get back the balance using the website after this time.
*/
function finish() onlyOwner public {
require(block.timestamp >= finishTime);
feeOwner.transfer(address(this).balance);
}
/**
* @dev Start the game
*
* Start a new game. Initialize game opponent, game time and status.
* @param _gameOpponent The game opponent contract address
* @param _gameTime The game begin time. optional
*/
function beginGame(address _gameOpponent, uint64 _gameTime) onlyOwner public {
require(_gameOpponent != address(this));
// 1514764800 = 2018-01-01
require(_gameTime == 0 || (_gameTime > 1514764800));
gameOpponent = _gameOpponent;
gameTime = _gameTime;
status = 0;
emit BeginGame(address(this), _gameOpponent, _gameTime);
}
/**
* @dev End the game with game final result.
*
* The function only allow to be called with the lose team or the draw team with large balance.
* We have this rule because the lose team or draw team will large balance need transfer balance to opposite side.
* This function will also change status of opposite team by calling transferFundAndEndGame function.
* So the function only need to be called one time for the home and away team.
* The new price will be recalculated based on the new balance and total supply.
*
* Balance transfer rule:
* 1. The rose team will transfer all balance to opposite side.
* 2. If the game is draw, the balances of two team will go fifty-fifty.
* 3. If game is canceled, the balance is not touched and the game states will be reset to initial states.
* 4. The fee will be 5% of each transfer amount.
* @param _gameOpponent The game opponent contract address
* @param _gameResult game result. 1=lose, 2=draw, 3=cancel, 4=win (not allow)
*/
function endGame(address _gameOpponent, uint8 _gameResult) onlyOwner public {
require(gameOpponent != address(0) && gameOpponent == _gameOpponent);
uint256 amount = address(this).balance;
uint256 opAmount = gameOpponent.balance;
require(_gameResult == 1 || (_gameResult == 2 && amount >= opAmount) || _gameResult == 3);
EthTeamContract op = EthTeamContract(gameOpponent);
if (_gameResult == 1) {
// Lose
if (amount > 0 && totalSupply_ > 0) {
uint256 lostAmount = amount;
// If opponent has supply
if (op.totalSupply() > 0) {
// fee is 5%
uint256 feeAmount = lostAmount.div(20);
lostAmount = lostAmount.sub(feeAmount);
feeOwner.transfer(feeAmount);
op.transferFundAndEndGame.value(lostAmount)();
} else {
// If opponent has not supply, then send the lose money to fee owner.
feeOwner.transfer(lostAmount);
op.transferFundAndEndGame();
}
} else {
op.transferFundAndEndGame();
}
} else if (_gameResult == 2) {
// Draw
if (amount > opAmount) {
lostAmount = amount.sub(opAmount).div(2);
if (op.totalSupply() > 0) {
// fee is 5%
feeAmount = lostAmount.div(20);
lostAmount = lostAmount.sub(feeAmount);
feeOwner.transfer(feeAmount);
op.transferFundAndEndGame.value(lostAmount)();
} else {
feeOwner.transfer(lostAmount);
op.transferFundAndEndGame();
}
} else if (amount == opAmount) {
op.transferFundAndEndGame();
} else {
// should not happen
revert();
}
} else if (_gameResult == 3) {
//canceled
op.transferFundAndEndGame();
} else {
// should not happen
revert();
}
endGameInternal();
if (totalSupply_ > 0) {
price = address(this).balance.div(totalSupply_);
}
emit EndGame(address(this), _gameOpponent, _gameResult);
}
/**
* @dev Reset team token states
*
*/
function endGameInternal() private {
gameOpponent = address(0);
gameTime = 0;
status = 0;
}
/**
* @dev Reset team states and recalculate the price.
*
* This function will be called by opponent team token after end game.
* It accepts the ETH transfer and recalculate the new price based on
* new balance and total supply.
*/
function transferFundAndEndGame() payable public {
require(gameOpponent != address(0) && gameOpponent == msg.sender);
if (msg.value > 0 && totalSupply_ > 0) {
price = address(this).balance.div(totalSupply_);
}
endGameInternal();
}
}
|
Change the fee owner. _feeOwner The new fee owner./
|
function changeFeeOwner(address _feeOwner) onlyOwner public {
require(_feeOwner != feeOwner && _feeOwner != address(0));
feeOwner = _feeOwner;
}
| 391,064 |
./full_match/1/0x3Bc988Da91b01d682C37e29f95bC0Ed18F3273Fc/sources/contracts/GraphcastRegistryV2.sol
|
Function to register GraphcastID address for an indexer Authorize an address to be a Graphcast ID. (unauthorize by setting address 0). Make sure the message sender is the provided indexer, or the message sender is an operator of the provided indexer by calling the Service Registry _indexer Indexer address to authorize Graphcast ID for _graphcastID Address to authorize as the Graphcast ID/ unset previous graphcastID
|
function setGraphcastIDFor(address _indexer, address _graphcastID) external virtual {
if (!_isAuth(_indexer))
revert UnauthorizedCaller(_indexer);
if (_graphcastID == msg.sender)
revert InvalidGraphcastID(_graphcastID);
if (_graphcastID != address(0) && graphcastIDRegistered[_graphcastID])
revert OccupiedGraphcastID(_graphcastID);
if (graphcastIDAuthorized[msg.sender] != address(0)){
graphcastIDRegistered[graphcastIDAuthorized[msg.sender]] = false;
}
graphcastIDAuthorized[msg.sender] = _graphcastID;
graphcastIDRegistered[_graphcastID] = true;
emit SetGraphcastID(_indexer, _graphcastID);
}
| 16,529,871 |
./full_match/80001/0x3A907E57Dca4a585b5cFE13Cbb438De03231a814/sources/contracts/ClampGovernance.sol
|
whitelist address that is allowed to vote based on CLAMP Voting mechanism
|
function whitelistAddress(uint _proposalId, address _voter) external onlyOwner{
require(_proposalId == proposalCount, "CLAMP: INVALID PROPOSAL ID");
ProposalState proposersLatestProposalState = state(_proposalId);
require(proposersLatestProposalState == ProposalState.Active ||
proposersLatestProposalState == ProposalState.Pending, "CLAMP: PROPOSAL NOT AVAILABLE");
bool isVoterExist = voterExist(_proposalId, _voter);
require(!isVoterExist, "CLAMP: VOTER ALREADY EXIST");
whitelistedAddresses[_proposalId].push(_voter);
emit NewVoter(_proposalId, _voter);
}
| 9,491,913 |
pragma solidity ^0.4.20;
import "./erc20.sol";
import "./TokenRescue.sol";
interface AccountRegistryInterface {
function canVoteOnProposal(address _voter, address _proposal) external view returns (bool);
}
contract FinneyVote is ERC20, TokenRescue {
uint256 supply = 0;
AccountRegistryInterface public accountRegistry = AccountRegistryInterface(0x000000002bb43c83eCe652d161ad0fa862129A2C);
address public owner = 0x4a6f6B9fF1fc974096f9063a45Fd12bD5B928AD1;
uint8 public constant decimals = 1;
string public symbol = "FV";
string public name = "FinneyVote";
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) approved;
function totalSupply() external constant returns (uint256) {
return supply;
}
function balanceOf(address _owner) external constant returns (uint256) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) external returns (bool) {
approved[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) external constant returns (uint256) {
return approved[_owner][_spender];
}
function transfer(address _to, uint256 _value) external returns (bool) {
if (balances[msg.sender] < _value) {
return false;
}
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) external returns (bool) {
if (balances[_from] < _value
|| approved[_from][msg.sender] < _value
|| _value == 0) {
return false;
}
approved[_from][msg.sender] -= _value;
balances[_from] -= _value;
balances[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function grant(address _to, uint256 _grant) external {
require(msg.sender == address(accountRegistry));
balances[_to] += _grant;
supply += _grant;
emit Transfer(address(0), _to, _grant);
}
// vote5 and vote1 are available for future use
function vote5(address _voter, address _votee) external {
require(balances[_voter] >= 10);
require(accountRegistry.canVoteOnProposal(_voter, msg.sender));
balances[_voter] -= 10;
balances[owner] += 5;
balances[_votee] += 5;
emit Transfer(_voter, owner, 5);
emit Transfer(_voter, _votee, 5);
}
function vote1(address _voter, address _votee) external {
require(balances[_voter] >= 10);
require(accountRegistry.canVoteOnProposal(_voter, msg.sender));
balances[_voter] -= 10;
balances[owner] += 9;
balances[_votee] += 1;
emit Transfer(_voter, owner, 9);
emit Transfer(_voter, _votee, 1);
}
function vote9(address _voter, address _votee) external {
require(balances[_voter] >= 10);
require(accountRegistry.canVoteOnProposal(_voter, msg.sender));
balances[_voter] -= 10;
balances[owner] += 1;
balances[_votee] += 9;
emit Transfer(_voter, owner, 1);
emit Transfer(_voter, _votee, 9);
}
modifier onlyOwner () {
require(msg.sender == owner);
_;
}
event Owner(address indexed owner);
event Registry(address indexed registry);
function transferOwnership(address _newOwner)
external onlyOwner {
uint256 balance = balances[owner];
balances[_newOwner] += balance;
balances[owner] = 0;
emit Transfer(owner, _newOwner, balance);
owner = _newOwner;
emit Owner(_newOwner);
}
function migrateAccountRegistry(AccountRegistryInterface _newAccountRegistry)
external onlyOwner {
accountRegistry = _newAccountRegistry;
emit Registry(_newAccountRegistry);
}
}
|
vote5 and vote1 are available for future use
|
function vote5(address _voter, address _votee) external {
require(balances[_voter] >= 10);
require(accountRegistry.canVoteOnProposal(_voter, msg.sender));
balances[_voter] -= 10;
balances[owner] += 5;
balances[_votee] += 5;
emit Transfer(_voter, owner, 5);
emit Transfer(_voter, _votee, 5);
}
| 5,540,590 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./../IAuditToken.sol";
import "./MemberHelpers.sol";
/**
* @title NodeOperations
* Additional function for Members
*/
contract NodeOperations is AccessControl {
using SafeMath for uint256;
MemberHelpers public memberHelpers;
address public auditToken;
Members public members;
address[] public nodeOperators;
address[] public CPAs;
uint256 public stakeRatio = 1000;
uint256 public stakeRatioDelegating = 1100;
uint256 public stakingRatioReferral = 9100;
uint256 public POWFee = 100e18;
struct nodeOperator {
bool isNodeOperator;
address[] delegations;
mapping(address => bool) isDelegating;
uint256 stakeAmount;
uint256 delegateAmount;
uint256 referralAmount;
uint256 POWAmount;
address delegatorLink;
bool noDelegations;
bool isCPA;
}
mapping(address => nodeOperator) public nodeOpStruct;
bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE");
bytes32 public constant SETTER_ROLE = keccak256("SETTER_ROLE");
event LogNodeOperatorToggled(address indexed user, string action);
event LogCPAToggled(address indexed user, string action);
event LogNoDelegateToggled(address indexed user, string action);
event LogRemoveDelegation(address indexed delegating, address indexed delegatee);
event LogDelegation(address indexed delegating, address indexed newDelegatee);
event LogDelegatedStakeRewardsIncreased(address indexed delegating, uint256 amount);
event LogReferralStakeRewardsIncreased(address indexed delegating, uint256 amount);
event LogStakingRewardsTransferredOut(address indexed user, uint256 amount);
event LogStakingRewardsClaimed(address indexed user, uint256 amount);
event LogStakeRewardsIncreased(address indexed validator, uint256 amount);
event LogGovernanceUpdate(uint256 params, string indexed action);
constructor(address _memberHelpers, address _auditToken, address _members) {
require(_memberHelpers != address(0), "NodeOperations:constructor - MemberHelpers address can't be 0");
require( _auditToken != address(0), "MemberHelpers:setCohort - Cohort address can't be 0");
memberHelpers = MemberHelpers(_memberHelpers);
auditToken = _auditToken;
members = Members(_members);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @dev check if caller is a controller
modifier isController(string memory source) {
string memory msgError = string(abi.encodePacked("NodeOperations(isController - Modifier):", source, "- Caller is not a controller"));
require(hasRole(CONTROLLER_ROLE, msg.sender),msgError);
_;
}
/// @dev check if caller is a setter
modifier isSetter {
require(hasRole(SETTER_ROLE, msg.sender), "NodeOperations:isSetter - Caller is not a setter");
_;
}
/// @dev check if user is validator
modifier isValidator(string memory source) {
string memory msgError = string(abi.encodePacked("NodeOperations(isValidator- Modifier):", source, "- You are not a validator"));
require( members.userMap(msg.sender, Members.UserType(1)), msgError);
_;
}
function updateStakeRatioDelegating(uint256 _newRatio) public isSetter() {
require(_newRatio != 0, "NodeOperations:updateStakeRatioDelegating - New value for the stake delegating ratio can't be 0");
stakeRatioDelegating = _newRatio;
emit LogGovernanceUpdate(_newRatio, "updateStakeRatioDelegating");
}
function updateStakingRatioReferral(uint256 _newRatio) public isSetter() {
require(_newRatio != 0, "NodeOperations:updateStakingRatioReferral - New value for the stake ratio can't be 0");
stakingRatioReferral = _newRatio;
emit LogGovernanceUpdate(_newRatio, "updateStakingRatioReferral");
}
function updateStakeRatio(uint256 _newRatio) public isSetter() {
require(_newRatio != 0, "NodeOperations:updateStakeRatio - New value for the stake ratio can't be 0");
stakeRatio = _newRatio;
emit LogGovernanceUpdate(_newRatio, "UpdateStakeRatio");
}
function updatePOWFee(uint256 _newFee) public isSetter() {
require(_newFee != 0, "NodeOperations:updatePOWFee - New value for the POWFee can't be 0");
POWFee = _newFee;
emit LogGovernanceUpdate(_newFee, "updatePOWFee");
}
function returnDelegatorLink(address operator) public view returns (address){
return nodeOpStruct[operator].delegatorLink;
}
function isNodeOperator(address operator) public view returns (bool) {
return nodeOpStruct[operator].isNodeOperator;
}
/***
* @dev return members of the staking pool
* @param poolOperator - owner of the pool
* @param name name of the user
* @return array of users with their deposit values
*/
function returnPoolList(address poolOperator)public view returns (address[] memory, uint256[] memory) {
address[] memory poolUsers = new address[](nodeOpStruct[poolOperator].delegations.length );
uint256[] memory poolUsersStakes = new uint256[](nodeOpStruct[poolOperator].delegations.length );
for (uint256 i = 0; i< nodeOpStruct[poolOperator].delegations.length ;i++) {
poolUsers[i]= nodeOpStruct[poolOperator].delegations[i];
poolUsersStakes[i] = memberHelpers.returnDepositAmount(poolUsers[i]);
}
return (poolUsers, poolUsersStakes);
}
/// @dev change Node operator status from on to off or the vice versa
function toggleNodeOperator( ) public isValidator("toggleNodeOperator") {
if (nodeOpStruct[msg.sender].isNodeOperator){
nodeOpStruct[msg.sender].isNodeOperator = false;
removeNodeOperator();
removeAlldelegations();
emit LogNodeOperatorToggled(msg.sender, "OFF");
}
else{
require(memberHelpers.returnDepositAmount(msg.sender) >= memberHelpers.minContribution(), "NodeOperations:toggelNodeOperator - Minimum stake amount not met.");
nodeOpStruct[msg.sender].isNodeOperator = true;
nodeOperators.push(msg.sender);
emit LogNodeOperatorToggled(msg.sender, "ON");
}
}
/// @dev change CPA status from on to off or vice versa
function toggleCPA( ) public isValidator("toggleCPA") {
if (nodeOpStruct[msg.sender].isCPA){
nodeOpStruct[msg.sender].isCPA = false;
removeCPA();
emit LogCPAToggled(msg.sender,"OFF");
}
else{
nodeOpStruct[msg.sender].isCPA = true;
CPAs.push(msg.sender);
emit LogCPAToggled(msg.sender,"ON");
}
}
/// @dev change no delegate flag from on to off or vice versa
function toggleNoDelegate( ) isValidator("toggleNoDelegate") public {
if (nodeOpStruct[msg.sender].noDelegations){
nodeOpStruct[msg.sender].noDelegations = false;
emit LogNoDelegateToggled(msg.sender, "OFF");
}
else{
removeAlldelegations();
nodeOpStruct[msg.sender].noDelegations = true;
emit LogNoDelegateToggled(msg.sender, "ON");
}
}
/// @dev remove CPA status
function removeCPA() internal {
for (uint256 i= 0; i < CPAs.length; i++) {
if (CPAs[i] == msg.sender){
CPAs[i] = CPAs[CPAs.length - 1];
CPAs.pop();
i = CPAs.length;
}
}
}
/// @dev remove Node operator status
function removeNodeOperator() internal {
for (uint256 i= 0; i < nodeOperators.length; i++) {
if (nodeOperators[i] == msg.sender){
nodeOperators[i] = nodeOperators[nodeOperators.length - 1];
nodeOperators.pop();
i = nodeOperators.length;
}
}
}
/// return all node operators
function returnNodeOperators() public view returns (address[] memory) {
return nodeOperators;
}
function returnNodeOperatorsCount() public view returns(uint256){
return nodeOperators.length;
}
/// return all CPAs
function returnCPAs() public view returns (address[] memory) {
return CPAs;
}
/// remove all delegations for specific pool operator
function removeAlldelegations() public {
for (uint256 i = nodeOpStruct[msg.sender].delegations.length ; i > 0; i--) {
address delegating = nodeOpStruct[msg.sender].delegations[i-1];
nodeOpStruct[msg.sender].delegations.pop();
nodeOpStruct[msg.sender].isDelegating[delegating] = false;
nodeOpStruct[delegating].delegatorLink = address(0x0);
}
}
/// remove delegation for pool member
function removeDelegation() public isValidator("removeDelegation") {
address oldDelegatee = nodeOpStruct[msg.sender].delegatorLink;
require(oldDelegatee != address(0x0), "NodeOperations:removeDelegation You are not delegating your stake yet.");
for (uint256 i = 0; i < nodeOpStruct[oldDelegatee].delegations.length; i++) {
if (nodeOpStruct[oldDelegatee].delegations[i] == msg.sender) {
nodeOpStruct[oldDelegatee].delegations[i] = nodeOpStruct[oldDelegatee].delegations[nodeOpStruct[oldDelegatee].delegations.length - 1];
nodeOpStruct[oldDelegatee].delegations.pop();
nodeOpStruct[oldDelegatee].isDelegating[msg.sender] = false;
nodeOpStruct[msg.sender].delegatorLink = address(0x0);
i= nodeOpStruct[oldDelegatee].delegations.length;
}
}
emit LogRemoveDelegation(msg.sender, oldDelegatee);
}
/***
* @dev delegate stake to the pool
* @param delegatee - owner of the pool
*/
function delegate(address delegatee) public isValidator("Delegate") {
require(!nodeOpStruct[msg.sender].isNodeOperator, "NodeOperations:delegagte - You are a node operator, first cancel this role and then delegate again. ");
require(!nodeOpStruct[delegatee].isDelegating[msg.sender], "NodeOperations:delegate - You are already delegating to this member.");
if (nodeOpStruct[msg.sender].delegatorLink != address(0x0))
removeDelegation();
nodeOpStruct[delegatee].delegations.push(msg.sender);
nodeOpStruct[msg.sender].delegatorLink = delegatee;
nodeOpStruct[delegatee].isDelegating[msg.sender] = true;
emit LogDelegation(msg.sender, delegatee);
}
/***
* @dev called by the Validations contract to increase POW amount of winning validator
* @param validator - winner of the validation task
* @param amount to aword to validator
*/
function increasePOWRewards(address validator, uint256 amount) public isController("increasePOWRewards") {
nodeOpStruct[validator].POWAmount = nodeOpStruct[validator].POWAmount.add(amount);
}
/***
* @dev called by the Validations contract to increase delegated stake rewards and referral rewards
* @param validator - validator for whom values are increased
*/
function increaseDelegatedStakeRewards(address validator) public isController("increaseDelegatedStakeRewards") {
uint256 referringReward;
for (uint256 i = 0; i < nodeOpStruct[validator].delegations.length ; i++) {
address delegating = nodeOpStruct[validator].delegations[i];
uint256 amount = memberHelpers.returnDepositAmount(delegating).div(stakeRatioDelegating);
nodeOpStruct[delegating].delegateAmount = nodeOpStruct[delegating].delegateAmount.add(amount);
referringReward = referringReward.add(memberHelpers.returnDepositAmount(delegating).div(stakingRatioReferral));
emit LogDelegatedStakeRewardsIncreased(delegating, amount);
}
if (referringReward > 0) {
nodeOpStruct[validator].referralAmount = nodeOpStruct[validator].referralAmount.add(referringReward);
emit LogReferralStakeRewardsIncreased(validator, referringReward);
}
}
/***
* @dev called by the Validations contract to increase pool operator stake reward amount
* @param validator - validator for whom values are increased
*/
function increaseStakeRewards(address validator) public isController("increaseStakeRewards") {
uint256 amount = memberHelpers.returnDepositAmount(validator).div(stakeRatio);
nodeOpStruct[validator].stakeAmount = nodeOpStruct[validator].stakeAmount.add(amount);
emit LogStakeRewardsIncreased(validator, amount);
}
/***
* @dev called by the Validator to claim their reward
* @param deliver - true if amount should be delivered into the wallet or stake deposit
*/
function claimStakeRewards(bool deliver) public {
uint256 stakeRewards = nodeOpStruct[msg.sender].stakeAmount;
uint256 delegateRewards = nodeOpStruct[msg.sender].delegateAmount;
uint256 powRewards = nodeOpStruct[msg.sender].POWAmount;
uint256 refRewards = nodeOpStruct[msg.sender].referralAmount;
uint256 payment = stakeRewards.add(powRewards).add(refRewards).add(delegateRewards);
nodeOpStruct[msg.sender].stakeAmount= 0;
nodeOpStruct[msg.sender].delegateAmount = 0;
nodeOpStruct[msg.sender].POWAmount = 0;
nodeOpStruct[msg.sender].referralAmount = 0;
if (deliver) {
IAuditToken(auditToken).mint(msg.sender, payment);
emit LogStakingRewardsTransferredOut(msg.sender, payment);
} else {
memberHelpers.increaseDeposit(msg.sender, payment);
IAuditToken(auditToken).mint(address(this), payment);
emit LogStakingRewardsClaimed(msg.sender, payment);
}
}
}
|
remove Node operator status
|
function removeNodeOperator() internal {
for (uint256 i= 0; i < nodeOperators.length; i++) {
if (nodeOperators[i] == msg.sender){
nodeOperators[i] = nodeOperators[nodeOperators.length - 1];
nodeOperators.pop();
i = nodeOperators.length;
}
}
}
| 1,752,846 |
pragma solidity ^0.5.17;
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @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, ERROR_MUL_OVERFLOW);
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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW);
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, ERROR_ADD_OVERFLOW);
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, ERROR_DIV_ZERO);
return a % b;
}
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library SafeERC20 {
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
_token.transfer.selector,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(address(_token), approveCallData);
}
function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) {
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
}
library PctHelpers {
using SafeMath for uint256;
uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000)
function isValid(uint16 _pct) internal pure returns (bool) {
return _pct <= PCT_BASE;
}
function pct(uint256 self, uint16 _pct) internal pure returns (uint256) {
return self.mul(uint256(_pct)) / PCT_BASE;
}
function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) {
return self.mul(_pct) / PCT_BASE;
}
function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) {
// No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16)
return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE;
}
}
/**
* @title Checkpointing - Library to handle a historic set of numeric values
*/
library Checkpointing {
uint256 private constant MAX_UINT192 = uint256(uint192(-1));
string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG";
string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE";
/**
* @dev To specify a value at a given point in time, we need to store two values:
* - `time`: unit-time value to denote the first time when a value was registered
* - `value`: a positive numeric value to registered at a given point in time
*
* Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used
* for it like block numbers, terms, etc.
*/
struct Checkpoint {
uint64 time;
uint192 value;
}
/**
* @dev A history simply denotes a list of checkpoints
*/
struct History {
Checkpoint[] history;
}
/**
* @dev Add a new value to a history for a given point in time. This function does not allow to add values previous
* to the latest registered value, if the value willing to add corresponds to the latest registered value, it
* will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function add(History storage self, uint64 _time, uint256 _value) internal {
require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG);
_add192(self, _time, uint192(_value));
}
/**
* @dev Fetch the latest registered value of history, it will return zero if there was no value registered
* @param self Checkpoints history to be queried
*/
function getLast(History storage self) internal view returns (uint256) {
uint256 length = self.history.length;
if (length > 0) {
return uint256(self.history[length - 1].value);
}
return 0;
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time that is not known
* how recent it is beforehand. It will return zero if there is no registered value or if given time is
* previous to the first registered value.
* It uses a binary search.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function get(History storage self, uint64 _time) internal view returns (uint256) {
return _binarySearch(self, _time);
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero
* if there is no registered value or if given time is previous to the first registered value.
* It uses a linear search starting from the end.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) {
return _backwardsLinearSearch(self, _time);
}
/**
* @dev Private function to add a new value to a history for a given point in time. This function does not allow to
* add values previous to the latest registered value, if the value willing to add corresponds to the latest
* registered value, it will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function _add192(History storage self, uint64 _time, uint192 _value) private {
uint256 length = self.history.length;
if (length == 0 || self.history[self.history.length - 1].time < _time) {
// If there was no value registered or the given point in time is after the latest registered value,
// we can insert it to the history directly.
self.history.push(Checkpoint(_time, _value));
} else {
// If the point in time given for the new value is not after the latest registered value, we must ensure
// we are only trying to update the latest value, otherwise we would be changing past data.
Checkpoint storage currentCheckpoint = self.history[length - 1];
require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE);
currentCheckpoint.value = _value;
}
}
/**
* @dev Private function to execute a backwards linear search to find the most recent registered past value of a
* history based on a given point in time. It will return zero if there is no registered value or if given time
* is previous to the first registered value. Note that this function will be more suitable when we already know
* that the time used to index the search is recent in the given history.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
uint256 index = length - 1;
Checkpoint storage checkpoint = self.history[index];
while (index > 0 && checkpoint.time > _time) {
index--;
checkpoint = self.history[index];
}
return checkpoint.time > _time ? 0 : uint256(checkpoint.value);
}
/**
* @dev Private function execute a binary search to find the most recent registered past value of a history based on
* a given point in time. It will return zero if there is no registered value or if given time is previous to
* the first registered value. Note that this function will be more suitable when don't know how recent the
* time used to index may be.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _binarySearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
// If the requested time is equal to or after the time of the latest registered value, return latest value
uint256 lastIndex = length - 1;
if (_time >= self.history[lastIndex].time) {
return uint256(self.history[lastIndex].value);
}
// If the requested time is previous to the first registered value, return zero to denote missing checkpoint
if (_time < self.history[0].time) {
return 0;
}
// Execute a binary search between the checkpointed times of the history
uint256 low = 0;
uint256 high = lastIndex;
while (high > low) {
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2;
Checkpoint storage checkpoint = self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1
high = mid - 1;
} else {
return uint256(checkpoint.value);
}
}
return uint256(self.history[low].value);
}
}
/**
* @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees.
* @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its
* children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf
* node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a
* checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow
* accessing historic information.
*
* Example of a checkpointed binary sum tree:
*
* CURRENT PREVIOUS
*
* Level 2 100 ---------------------------------------- 70
* ______|_______ ______|_______
* / \ / \
* Level 1 34 66 ------------------------- 23 47
* _____|_____ _____|_____ _____|_____ _____|_____
* / \ / \ / \ / \
* Level 0 22 12 53 13 ----------- 22 1 17 30
*
*/
library HexSumTree {
using SafeMath for uint256;
using Checkpointing for Checkpointing.History;
string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW";
string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST";
string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS";
string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES";
// Constants used to perform tree computations
// To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN
// The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64)
uint256 private constant CHILDREN = 16;
uint256 private constant BITS_IN_NIBBLE = 4;
// All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree.
uint256 private constant ITEMS_LEVEL = 0;
// Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys
// starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys
// are computed based on their level and their children keys.
uint256 private constant BASE_KEY = 0;
// Timestamp used to checkpoint the first value of the tree height during initialization
uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0);
/**
* @dev The tree is stored using the following structure:
* - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value).
* - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children.
* - nextKey: The next key to be used to identify the next new value that will be inserted into the tree.
*/
struct Tree {
uint256 nextKey;
Checkpointing.History height;
mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes;
}
/**
* @dev Search params to traverse the tree caching previous results:
* - time: Point in time to query the values being searched, this value shouldn't change during a search
* - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves
* - parentKey: Key of the parent of the nodes being analyzed at the given level for the search
* - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list
* - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total
*/
struct SearchParams {
uint64 time;
uint256 level;
uint256 parentKey;
uint256 foundValues;
uint256 visitedTotal;
}
/**
* @dev Initialize tree setting the next key and first height checkpoint
*/
function init(Tree storage self) internal {
self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1);
self.nextKey = BASE_KEY;
}
/**
* @dev Insert a new item to the tree at given point in time
* @param _time Point in time to register the given value
* @param _value New numeric value to be added to the tree
* @return Unique key identifying the new value inserted
*/
function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) {
// As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be
// always incrementing, starting from zero. Add a new level if necessary.
uint256 key = self.nextKey++;
_addLevelIfNecessary(self, key, _time);
// If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of
// the tree if necessary, and finally update sums cached in all the non-leaf nodes.
if (_value > 0) {
_add(self, ITEMS_LEVEL, key, _time, _value);
_updateSums(self, key, _time, _value, true);
}
return key;
}
/**
* @dev Set the value of a leaf node indexed by its key at given point in time
* @param _time Point in time to set the given value
* @param _key Key of the leaf node to be set in the tree
* @param _value New numeric value to be set for the given key
*/
function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal {
require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST);
// Set the new value for the requested leaf node
uint256 lastValue = getItem(self, _key);
_add(self, ITEMS_LEVEL, _key, _time, _value);
// Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update.
if (_value > lastValue) {
_updateSums(self, _key, _time, _value - lastValue, true);
} else if (_value < lastValue) {
_updateSums(self, _key, _time, lastValue - _value, false);
}
}
/**
* @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta
* @param _key Key of the leaf node to be updated in the tree
* @param _time Point in time to update the given value
* @param _delta Numeric delta to update the value of the given key
* @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value
*/
function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal {
require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST);
// Update the value of the requested leaf node based on the given delta
uint256 lastValue = getItem(self, _key);
uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta);
_add(self, ITEMS_LEVEL, _key, _time, newValue);
// Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update.
_updateSums(self, _key, _time, _delta, _positive);
}
/**
* @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest
* high value in case a value cannot be found. This function assumes the given list of given values to be
* searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results.
* @param _values Ordered list of values to be searched in the tree
* @param _time Point in time to query the values being searched
* @return keys List of keys found for each requested value in the same order
* @return values List of node values found for each requested value in the same order
*/
function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view
returns (uint256[] memory keys, uint256[] memory values)
{
require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES);
// Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total
uint256 total = getRecentTotalAt(self, _time);
// No need for SafeMath: positive length of array already checked
require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS);
// Build search params for the first iteration
uint256 rootLevel = getRecentHeightAt(self, _time);
SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0);
// These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies
uint256 length = _values.length;
keys = new uint256[](length);
values = new uint256[](length);
_search(self, _values, searchParams, keys, values);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree
*/
function getTotal(Tree storage self) internal view returns (uint256) {
uint256 rootLevel = getHeight(self);
return getNode(self, rootLevel, BASE_KEY);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time
* It uses a binary search for the root node, a linear one for the height.
* @param _time Point in time to query the sum of all the items (leaves) stored in the tree
*/
function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) {
uint256 rootLevel = getRecentHeightAt(self, _time);
return getNodeAt(self, rootLevel, BASE_KEY, _time);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time
* It uses a linear search starting from the end.
* @param _time Point in time to query the sum of all the items (leaves) stored in the tree
*/
function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) {
uint256 rootLevel = getRecentHeightAt(self, _time);
return getRecentNodeAt(self, rootLevel, BASE_KEY, _time);
}
/**
* @dev Tell the value of a certain leaf indexed by a given key
* @param _key Key of the leaf node querying the value of
*/
function getItem(Tree storage self, uint256 _key) internal view returns (uint256) {
return getNode(self, ITEMS_LEVEL, _key);
}
/**
* @dev Tell the value of a certain leaf indexed by a given key at a given point in time
* It uses a binary search.
* @param _key Key of the leaf node querying the value of
* @param _time Point in time to query the value of the requested leaf
*/
function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) {
return getNodeAt(self, ITEMS_LEVEL, _key, _time);
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
*/
function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) {
return self.nodes[_level][_key].getLast();
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time
* It uses a binary search.
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
* @param _time Point in time to query the value of the requested node
*/
function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) {
return self.nodes[_level][_key].get(_time);
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time
* It uses a linear search starting from the end.
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
* @param _time Point in time to query the value of the requested node
*/
function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) {
return self.nodes[_level][_key].getRecent(_time);
}
/**
* @dev Tell the height of the tree
*/
function getHeight(Tree storage self) internal view returns (uint256) {
return self.height.getLast();
}
/**
* @dev Tell the height of the tree at a given point in time
* It uses a linear search starting from the end.
* @param _time Point in time to query the height of the tree
*/
function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) {
return self.height.getRecent(_time);
}
/**
* @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated
* @param _key Key of the leaf node to update the ancestors of
* @param _time Point in time to update the ancestors' values of the given leaf node
* @param _delta Numeric delta to update the ancestors' values of the given leaf node
* @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values
*/
function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private {
uint256 mask = uint256(-1);
uint256 ancestorKey = _key;
uint256 currentHeight = getHeight(self);
for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) {
// Build a mask to get the key of the ancestor at a certain level. For example:
// Level 0: leaves don't have children
// Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves)
// Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves)
// ...
// Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height)
mask = mask << BITS_IN_NIBBLE;
// The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles
// of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a
// certain level applying the mask to the ancestor's key of the previous level. Note that for the first
// iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated.
ancestorKey = ancestorKey & mask;
// Update value
uint256 lastValue = getNode(self, level, ancestorKey);
uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta);
_add(self, level, ancestorKey, _time, newValue);
}
// Check if there was an overflow. Note that we only need to check the value stored in the root since the
// sum only increases going up through the tree.
require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW);
}
/**
* @dev Private function to add a new level to the tree based on a new key that will be inserted
* @param _newKey New key willing to be inserted in the tree
* @param _time Point in time when the new key will be inserted
*/
function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private {
uint256 currentHeight = getHeight(self);
if (_shouldAddLevel(currentHeight, _newKey)) {
// Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we
// are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of
// this system having 2^256 items inserted is unrealistic.
uint256 newHeight = currentHeight + 1;
uint256 rootValue = getNode(self, currentHeight, BASE_KEY);
_add(self, newHeight, BASE_KEY, _time, rootValue);
self.height.add(_time, newHeight);
}
}
/**
* @dev Private function to register a new value in the history of a node at a given point in time
* @param _level Level of the node to add a new value at a given point in time to
* @param _key Key of the node to add a new value at a given point in time to
* @param _time Point in time to register a value for the given node
* @param _value Numeric value to be registered for the given node at a given point in time
*/
function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private {
self.nodes[_level][_key].add(_time, _value);
}
/**
* @dev Recursive pre-order traversal function
* Every time it checks a node, it traverses the input array to find the initial subset of elements that are
* below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always
* the same, to avoid making extra copies, it just passes the number of values already found , to avoid
* checking values that went through a different branch. The same happens with the result lists of keys and
* values, these are the same on every recursion step. The visited total is carried over each iteration to
* avoid having to subtract all elements in the array.
* @param _values Ordered list of values to be searched in the tree
* @param _params Search parameters for the current recursive step
* @param _resultKeys List of keys found for each requested value in the same order
* @param _resultValues List of node values found for each requested value in the same order
*/
function _search(
Tree storage self,
uint256[] memory _values,
SearchParams memory _params,
uint256[] memory _resultKeys,
uint256[] memory _resultValues
)
private
view
{
uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE);
for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) {
// Return if we already found enough values
if (_params.foundValues >= _values.length) {
break;
}
// Build child node key shifting the child number to the position of the less significant nibble of
// the keys for the level being analyzed, and adding it to the key of the parent node. For example,
// for a tree with height 5, if we are checking the children of the second node of the level 3, whose
// key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are:
// Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000
// Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100
// Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200
// ...
// Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00
uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble);
uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time);
// Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous
// subset starting from the beginning, so we only need to know the length of that subset.
uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue);
uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal);
// If there are some values included in the subtree of the child node, visit them
if (subtreeIncludedValues > 0) {
// If the child node being analyzed is a leaf, add it to the list of results a number of times equals
// to the number of values that were included in it. Otherwise, descend one level.
if (_params.level == ITEMS_LEVEL) {
_copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues);
} else {
SearchParams memory nextLevelParams = SearchParams(
_params.time,
_params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero
childNodeKey,
_params.foundValues,
_params.visitedTotal
);
_search(self, _values, nextLevelParams, _resultKeys, _resultValues);
}
// Update the number of values that were already found
_params.foundValues = _params.foundValues.add(subtreeIncludedValues);
}
// Update the visited total for the next node in this level
_params.visitedTotal = newVisitedTotal;
}
}
/**
* @dev Private function to check if a new key can be added to the tree based on the current height of the tree
* @param _currentHeight Current height of the tree to check if it supports adding the given key
* @param _newKey Key willing to be added to the tree with the given current height
* @return True if the current height of the tree should be increased to add the new key, false otherwise.
*/
function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) {
// Build a mask that will match all the possible keys for the given height. For example:
// Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys)
// Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys)
// ...
// Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height)
uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE);
uint256 mask = uint256(-1) << shift;
// Check if the given key can be represented in the tree with the current given height using the mask.
return (_newKey & mask) != 0;
}
/**
* @dev Private function to tell how many values of a list can be found in a subtree
* @param _values List of values being searched in ascending order
* @param _foundValues Number of values that were already found and should be ignore
* @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it
* @return Number of values in the list that are included in the given subtree
*/
function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) {
// Look for all the values that can be found in the given subtree
uint256 i = _foundValues;
while (i < _values.length && _values[i] < _subtreeTotal) {
i++;
}
return i - _foundValues;
}
/**
* @dev Private function to copy a node a given number of times to a results list. This function assumes the given
* results list have enough size to support the requested copy.
* @param _from Index of the results list to start copying the given node
* @param _times Number of times the given node will be copied
* @param _key Key of the node to be copied
* @param _resultKeys Lists of key results to copy the given node key to
* @param _value Value of the node to be copied
* @param _resultValues Lists of value results to copy the given node value to
*/
function _copyFoundNode(
uint256 _from,
uint256 _times,
uint256 _key,
uint256[] memory _resultKeys,
uint256 _value,
uint256[] memory _resultValues
)
private
pure
{
for (uint256 i = 0; i < _times; i++) {
_resultKeys[_from + i] = _key;
_resultValues[_from + i] = _value;
}
}
}
/**
* @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree`
*/
library GuardiansTreeSortition {
using SafeMath for uint256;
using HexSumTree for HexSumTree.Tree;
string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH";
string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH";
/**
* @dev Search random items in the tree based on certain restrictions
* @param _termRandomness Randomness to compute the seed for the draft
* @param _disputeId Identification number of the dispute to draft guardians for
* @param _termId Current term when the draft is being computed
* @param _selectedGuardians Number of guardians already selected for the draft
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _roundRequestedGuardians Total number of guardians requested to be drafted
* @param _sortitionIteration Number of sortitions already performed for the given draft
* @return guardiansIds List of guardian ids obtained based on the requested search
* @return guardiansBalances List of active balances for each guardian obtained based on the requested search
*/
function batchedRandomSearch(
HexSumTree.Tree storage tree,
bytes32 _termRandomness,
uint256 _disputeId,
uint64 _termId,
uint256 _selectedGuardians,
uint256 _batchRequestedGuardians,
uint256 _roundRequestedGuardians,
uint256 _sortitionIteration
)
internal
view
returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances)
{
(uint256 low, uint256 high) = getSearchBatchBounds(
tree,
_termId,
_selectedGuardians,
_batchRequestedGuardians,
_roundRequestedGuardians
);
uint256[] memory balances = _computeSearchRandomBalances(
_termRandomness,
_disputeId,
_sortitionIteration,
_batchRequestedGuardians,
low,
high
);
(guardiansIds, guardiansBalances) = tree.search(balances, _termId);
require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH);
require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH);
}
/**
* @dev Get the bounds for a draft batch based on the active balances of the guardians
* @param _termId Term ID of the active balances that will be used to compute the boundaries
* @param _selectedGuardians Number of guardians already selected for the draft
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _roundRequestedGuardians Total number of guardians requested to be drafted
* @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch
* @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch
*/
function getSearchBatchBounds(
HexSumTree.Tree storage tree,
uint64 _termId,
uint256 _selectedGuardians,
uint256 _batchRequestedGuardians,
uint256 _roundRequestedGuardians
)
internal
view
returns (uint256 low, uint256 high)
{
uint256 totalActiveBalance = tree.getRecentTotalAt(_termId);
low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians);
uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians);
high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians);
}
/**
* @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch
* @param _termRandomness Randomness to compute the seed for the draft
* @param _disputeId Identification number of the dispute to draft guardians for (for randomness)
* @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness)
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians
* @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians
* @return Random list of active balances to be searched in the guardians tree for the given draft batch
*/
function _computeSearchRandomBalances(
bytes32 _termRandomness,
uint256 _disputeId,
uint256 _sortitionIteration,
uint256 _batchRequestedGuardians,
uint256 _lowBatchBound,
uint256 _highBatchBound
)
internal
pure
returns (uint256[] memory)
{
// Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the
// random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10).
require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH);
uint256 interval = _highBatchBound - _lowBatchBound;
// Compute an ordered list of random active balance to be searched in the guardians tree
uint256[] memory balances = new uint256[](_batchRequestedGuardians);
for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) {
// Compute a random seed using:
// - The inherent randomness associated to the term from blockhash
// - The disputeId, so 2 disputes in the same term will have different outcomes
// - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance
// - The guardian number in this batch
bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber));
// Compute a random active balance to be searched in the guardians tree using the generated seed within the
// boundaries computed for the current batch.
balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval);
// Make sure it's ordered, flip values if necessary
for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) {
uint256 tmp = balances[i - 1];
balances[i - 1] = balances[i];
balances[i] = tmp;
}
}
return balances;
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ILockManager {
/**
* @dev Tell whether a user can unlock a certain amount of tokens
*/
function canUnlock(address user, uint256 amount) external view returns (bool);
}
/*
* SPDX-License-Identifier: MIT
*/
interface IGuardiansRegistry {
/**
* @dev Assign a requested amount of guardian tokens to a guardian
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external;
/**
* @dev Burn a requested amount of guardian tokens
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external;
/**
* @dev Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length);
/**
* @dev Slash a set of guardians based on their votes compared to the winning ruling
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
returns (uint256 collectedTokens);
/**
* @dev Try to collect a certain amount of tokens from a guardian for the next term
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool);
/**
* @dev Lock a guardian's withdrawals until a certain term ID
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external;
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256);
/**
* @dev Tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
contract ACL {
string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE";
string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN";
string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT";
enum BulkOp { Grant, Revoke, Freeze }
address internal constant FREEZE_FLAG = address(1);
address internal constant ANY_ADDR = address(-1);
// List of all roles assigned to different addresses
mapping (bytes32 => mapping (address => bool)) public roles;
event Granted(bytes32 indexed id, address indexed who);
event Revoked(bytes32 indexed id, address indexed who);
event Frozen(bytes32 indexed id);
/**
* @dev Tell whether an address has a role assigned
* @param _who Address being queried
* @param _id ID of the role being checked
* @return True if the requested address has assigned the given role, false otherwise
*/
function hasRole(address _who, bytes32 _id) public view returns (bool) {
return roles[_id][_who] || roles[_id][ANY_ADDR];
}
/**
* @dev Tell whether a role is frozen
* @param _id ID of the role being checked
* @return True if the given role is frozen, false otherwise
*/
function isRoleFrozen(bytes32 _id) public view returns (bool) {
return roles[_id][FREEZE_FLAG];
}
/**
* @dev Internal function to grant a role to a given address
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function _grant(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE);
if (!hasRole(_who, _id)) {
roles[_id][_who] = true;
emit Granted(_id, _who);
}
}
/**
* @dev Internal function to revoke a role from a given address
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function _revoke(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
if (hasRole(_who, _id)) {
roles[_id][_who] = false;
emit Revoked(_id, _who);
}
}
/**
* @dev Internal function to freeze a role
* @param _id ID of the role to be frozen
*/
function _freeze(bytes32 _id) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
roles[_id][FREEZE_FLAG] = true;
emit Frozen(_id);
}
/**
* @dev Internal function to enact a bulk list of ACL operations
*/
function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal {
require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT);
for (uint256 i = 0; i < _op.length; i++) {
BulkOp op = _op[i];
if (op == BulkOp.Grant) {
_grant(_id[i], _who[i]);
} else if (op == BulkOp.Revoke) {
_revoke(_id[i], _who[i]);
} else if (op == BulkOp.Freeze) {
_freeze(_id[i]);
}
}
}
}
contract ModuleIds {
// DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER"))
bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6;
// GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY"))
bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe;
// Voting module ID - keccak256(abi.encodePacked("VOTING"))
bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346;
// PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK"))
bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418;
// Treasury module ID - keccak256(abi.encodePacked("TREASURY"))
bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7;
}
interface IModulesLinker {
/**
* @notice Update the implementations of a list of modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external;
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
interface IClock {
/**
* @dev Ensure that the current term of the clock is up-to-date
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64);
/**
* @dev Transition up to a certain number of terms to leave the clock up-to-date
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64);
/**
* @dev Ensure that a certain term has its randomness set
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32);
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64);
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64);
/**
* @dev Tell the number of terms the clock should transition to be up-to-date
* @return Number of terms the clock should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64);
/**
* @dev Tell the information related to a term based on its ID
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view returns (bytes32);
}
contract CourtClock is IClock, TimeHelpers {
using SafeMath64 for uint64;
string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST";
string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG";
string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET";
string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE";
string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME";
string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS";
string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS";
string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT";
string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME";
// Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date
uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1;
// Max duration in seconds that a term can last
uint64 internal constant MAX_TERM_DURATION = 365 days;
// Max time until first term starts since contract is deployed
uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION;
struct Term {
uint64 startTime; // Timestamp when the term started
uint64 randomnessBN; // Block number for entropy
bytes32 randomness; // Entropy from randomnessBN block hash
}
// Duration in seconds for each term of the Court
uint64 private termDuration;
// Last ensured term id
uint64 private termId;
// List of Court terms indexed by id
mapping (uint64 => Term) private terms;
event Heartbeat(uint64 previousTermId, uint64 currentTermId);
event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime);
/**
* @dev Ensure a certain term has already been processed
* @param _termId Identification number of the term to be checked
*/
modifier termExists(uint64 _termId) {
require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
*/
constructor(uint64[2] memory _termParams) public {
uint64 _termDuration = _termParams[0];
uint64 _firstTermStartTime = _termParams[1];
require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG);
require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME);
require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME);
termDuration = _termDuration;
// No need for SafeMath: we already checked values above
terms[0].startTime = _firstTermStartTime - _termDuration;
}
/**
* @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED`
* terms, the heartbeat function must be called manually instead.
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64) {
return _ensureCurrentTerm();
}
/**
* @notice Transition up to `_maxRequestedTransitions` terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) {
return _heartbeat(_maxRequestedTransitions);
}
/**
* @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there
* were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given
* round will be able to be drafted in the following term.
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32) {
// If the randomness for the given term was already computed, return
uint64 currentTermId = termId;
Term storage term = terms[currentTermId];
bytes32 termRandomness = term.randomness;
if (termRandomness != bytes32(0)) {
return termRandomness;
}
// Compute term randomness
bytes32 newRandomness = _computeTermRandomness(currentTermId);
require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE);
term.randomness = newRandomness;
return newRandomness;
}
/**
* @dev Tell the term duration of the Court
* @return Duration in seconds of the Court term
*/
function getTermDuration() external view returns (uint64) {
return termDuration;
}
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64) {
return _lastEnsuredTermId();
}
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64) {
return _currentTermId();
}
/**
* @dev Tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64) {
return _neededTermTransitions();
}
/**
* @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the
* information returned won't be computed yet. This function allows querying future terms that were not computed yet.
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) {
Term storage term = terms[_termId];
return (term.startTime, term.randomnessBN, term.randomness);
}
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) {
return _computeTermRandomness(_termId);
}
/**
* @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than
* `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually.
* @return Identification number of the resultant term ID after executing the corresponding transitions
*/
function _ensureCurrentTerm() internal returns (uint64) {
// Check the required number of transitions does not exceeds the max allowed number to be processed automatically
uint64 requiredTransitions = _neededTermTransitions();
require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS);
// If there are no transitions pending, return the last ensured term id
if (uint256(requiredTransitions) == 0) {
return termId;
}
// Process transition if there is at least one pending
return _heartbeat(requiredTransitions);
}
/**
* @dev Internal function to transition the Court terms up to a requested number of terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the resultant term ID after executing the requested transitions
*/
function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) {
// Transition the minimum number of terms between the amount requested and the amount actually needed
uint64 neededTransitions = _neededTermTransitions();
uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions);
require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS);
uint64 blockNumber = getBlockNumber64();
uint64 previousTermId = termId;
uint64 currentTermId = previousTermId;
for (uint256 transition = 1; transition <= transitions; transition++) {
// Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64,
// even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is
// already assumed to fit in uint64.
Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
// Set the start time of the new term. Note that we are using a constant term duration value to guarantee
// equally long terms, regardless of heartbeats.
currentTerm.startTime = previousTerm.startTime.add(termDuration);
// In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a
// block number that is set once the term has started. Note that this information could not be known beforehand.
currentTerm.randomnessBN = blockNumber + 1;
}
termId = currentTermId;
emit Heartbeat(previousTermId, currentTermId);
return currentTermId;
}
/**
* @dev Internal function to delay the first term start time only if it wasn't reached yet
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function _delayStartTime(uint64 _newFirstTermStartTime) internal {
require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT);
Term storage term = terms[0];
uint64 currentFirstTermStartTime = term.startTime.add(termDuration);
require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME);
// No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration`
term.startTime = _newFirstTermStartTime - termDuration;
emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime);
}
/**
* @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior.
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal;
/**
* @dev Internal function to tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function _lastEnsuredTermId() internal view returns (uint64) {
return termId;
}
/**
* @dev Internal function to tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function _currentTermId() internal view returns (uint64) {
return termId.add(_neededTermTransitions());
}
/**
* @dev Internal function to tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function _neededTermTransitions() internal view returns (uint64) {
// Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case,
// no term transitions are required.
uint64 currentTermStartTime = terms[termId].startTime;
if (getTimestamp64() < currentTermStartTime) {
return uint64(0);
}
// No need for SafeMath: we already know that the start time of the current term is in the past
return (getTimestamp64() - currentTermStartTime) / termDuration;
}
/**
* @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This
* function assumes the given term exists. To determine the randomness factor for a term we use the hash of a
* block number that is set once the term has started to ensure it cannot be known beforehand. Note that the
* hash function being used only works for the 256 most recent block numbers.
* @param _termId Identification number of the term being queried
* @return Randomness computed for the given term
*/
function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) {
Term storage term = terms[_termId];
require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET);
return blockhash(term.randomnessBN);
}
}
interface IConfig {
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
}
contract CourtConfigData {
struct Config {
FeesConfig fees; // Full fees-related config
DisputesConfig disputes; // Full disputes-related config
uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court
}
struct FeesConfig {
IERC20 token; // ERC20 token to be used for the fees of the Court
uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000)
uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians
}
struct DisputesConfig {
uint64 evidenceTerms; // Max submitting evidence period duration in terms
uint64 commitTerms; // Committing period duration in terms
uint64 revealTerms; // Revealing period duration in terms
uint64 appealTerms; // Appealing period duration in terms
uint64 appealConfirmTerms; // Confirmation appeal period duration in terms
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round
uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal
uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked
uint256 maxRegularAppealRounds; // Before the final appeal
uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000)
uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000)
}
struct DraftConfig {
IERC20 feeToken; // ERC20 token to be used for the fees of the Court
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
}
}
contract CourtConfig is IConfig, CourtConfigData {
using SafeMath64 for uint64;
using PctHelpers for uint256;
string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM";
string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT";
string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT";
string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS";
string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION";
string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER";
string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR";
string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR";
string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE";
// Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year)
uint64 internal constant MAX_ADJ_STATE_DURATION = 8670;
// Cap the max number of regular appeal rounds
uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10;
// Future term ID in which a config change has been scheduled
uint64 private configChangeTermId;
// List of all the configs used in the Court
Config[] private configs;
// List of configs indexed by id
mapping (uint64 => uint256) private configIdByTerm;
event NewConfig(uint64 fromTermId, uint64 courtConfigId);
/**
* @dev Constructor function
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
{
// Leave config at index 0 empty for non-scheduled config changes
configs.length = 1;
_setConfig(
0,
0,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
/**
* @dev Tell the term identification number of the next scheduled config change
* @return Term identification number of the next scheduled config change
*/
function getConfigChangeTermId() external view returns (uint64) {
return configChangeTermId;
}
/**
* @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none
* @param _termId Identification number of the new current term that has been transitioned
*/
function _ensureTermConfig(uint64 _termId) internal {
// If the term being transitioned had no config change scheduled, keep the previous one
uint256 currentConfigId = configIdByTerm[_termId];
if (currentConfigId == 0) {
uint256 previousConfigId = configIdByTerm[_termId.sub(1)];
configIdByTerm[_termId] = previousConfigId;
}
}
/**
* @dev Assumes that sender it's allowed (either it's from governor or it's on init)
* @param _termId Identification number of the current Court term
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees.
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _setConfig(
uint64 _termId,
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
internal
{
// If the current term is not zero, changes must be scheduled at least after the current period.
// No need to ensure delays for on-going disputes since these already use their creation term for that.
require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM);
// Make sure appeal collateral factors are greater than zero
require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR);
// Make sure the given penalty and final round reduction pcts are not greater than 100%
require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT);
require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT);
// Disputes must request at least one guardian to be drafted initially
require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER);
// Prevent that further rounds have zero guardians
require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR);
// Make sure the max number of appeals allowed does not reach the limit
uint256 _maxRegularAppealRounds = _roundParams[2];
bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT;
require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS);
// Make sure each adjudication round phase duration is valid
for (uint i = 0; i < _roundStateDurations.length; i++) {
require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION);
}
// Make sure min active balance is not zero
require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE);
// If there was a config change already scheduled, reset it (in that case we will overwrite last array item).
// Otherwise, schedule a new config.
if (configChangeTermId > _termId) {
configIdByTerm[configChangeTermId] = 0;
} else {
configs.length++;
}
uint64 courtConfigId = uint64(configs.length - 1);
Config storage config = configs[courtConfigId];
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _maxRegularAppealRounds,
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
configIdByTerm[_fromTermId] = courtConfigId;
configChangeTermId = _fromTermId;
emit NewConfig(_fromTermId, courtConfigId);
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
FeesConfig storage feesConfig = config.fees;
feeToken = feesConfig.token;
fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee];
DisputesConfig storage disputesConfig = config.disputes;
roundStateDurations = [
disputesConfig.evidenceTerms,
disputesConfig.commitTerms,
disputesConfig.revealTerms,
disputesConfig.appealTerms,
disputesConfig.appealConfirmTerms
];
pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction];
roundParams = [
disputesConfig.firstRoundGuardiansNumber,
disputesConfig.appealStepFactor,
uint64(disputesConfig.maxRegularAppealRounds),
disputesConfig.finalRoundLockTerms
];
appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor];
minActiveBalance = config.minActiveBalance;
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct);
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Minimum amount of guardian tokens that can be activated at the given term
*/
function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return config.minActiveBalance;
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Court config for the given term
*/
function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) {
uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId);
return configs[id];
}
/**
* @dev Internal function to get the Court config ID for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Identification number of the config for the given terms
*/
function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
// If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config
if (_termId <= _lastEnsuredTermId) {
return configIdByTerm[_termId];
}
// If the given term is in the future but there is a config change scheduled before it, use the incoming config
uint64 scheduledChangeTermId = configChangeTermId;
if (scheduledChangeTermId <= _termId) {
return configIdByTerm[scheduledChangeTermId];
}
// If no changes are scheduled, use the Court config of the last ensured term
return configIdByTerm[_lastEnsuredTermId];
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface IArbitrator {
/**
* @dev Create a dispute over the Arbitrable sender with a number of possible rulings
* @param _possibleRulings Number of possible rulings allowed for the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _disputeId Id of the dispute in the Court
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence related to the dispute
*/
function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(uint256 _disputeId) external;
/**
* @notice Rule dispute #`_disputeId` if ready
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Subject associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling);
/**
* @dev Tell the dispute fees information to create a dispute
* @return recipient Address where the corresponding dispute fees must be transferred to
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees that must be allowed to the recipient
*/
function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell the payments recipient address
* @return Address of the payments recipient module
*/
function getPaymentsRecipient() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @dev The Arbitrable instances actually don't require to follow any specific interface.
* Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances.
*/
contract IArbitrable {
/**
* @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator
* @param arbitrator IArbitrator instance ruling the dispute
* @param disputeId Identification number of the dispute being ruled by the arbitrator
* @param ruling Ruling given by the arbitrator
*/
event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling);
}
interface IDisputeManager {
enum DisputeState {
PreDraft,
Adjudicating,
Ruled
}
enum AdjudicationState {
Invalid,
Committing,
Revealing,
Appealing,
ConfirmingAppeal,
Ended
}
/**
* @dev Create a dispute to be drafted in a future term
* @param _subject Arbitrable instance creating the dispute
* @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _subject Arbitrable instance submitting the dispute
* @param _disputeId Identification number of the dispute receiving new evidence
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence of the dispute
*/
function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _subject IArbitrable instance requesting to close the evidence submission period
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external;
/**
* @dev Draft guardians for the next round of a dispute
* @param _disputeId Identification number of the dispute to be drafted
*/
function draft(uint256 _disputeId) external;
/**
* @dev Appeal round of a dispute in favor of a certain ruling
* @param _disputeId Identification number of the dispute being appealed
* @param _roundId Identification number of the dispute round being appealed
* @param _ruling Ruling appealing a dispute round in favor of
*/
function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Confirm appeal for a round of a dispute in favor of a ruling
* @param _disputeId Identification number of the dispute confirming an appeal of
* @param _roundId Identification number of the dispute round confirming an appeal of
* @param _ruling Ruling being confirmed against a dispute round appeal
*/
function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Compute the final ruling for a dispute
* @param _disputeId Identification number of the dispute to compute its final ruling
* @return subject Arbitrable instance associated to the dispute
* @return finalRuling Final ruling decided for the given dispute
*/
function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling);
/**
* @dev Settle penalties for a round of a dispute
* @param _disputeId Identification number of the dispute to settle penalties for
* @param _roundId Identification number of the dispute round to settle penalties for
* @param _guardiansToSettle Maximum number of guardians to be slashed in this call
*/
function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external;
/**
* @dev Claim rewards for a round of a dispute for guardian
* @dev For regular rounds, it will only reward winning guardians
* @param _disputeId Identification number of the dispute to settle rewards for
* @param _roundId Identification number of the dispute round to settle rewards for
* @param _guardian Address of the guardian to settle their rewards
*/
function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external;
/**
* @dev Settle appeal deposits for a round of a dispute
* @param _disputeId Identification number of the dispute to settle appeal deposits for
* @param _roundId Identification number of the dispute round to settle appeal deposits for
*/
function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external;
/**
* @dev Tell the amount of token fees required to create a dispute
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees to be paid for a dispute at the given term
*/
function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell information of a certain dispute
* @param _disputeId Identification number of the dispute being queried
* @return subject Arbitrable subject being disputed
* @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled
* @return finalRuling The winning ruling in case the dispute is finished
* @return lastRoundId Identification number of the last round created for the dispute
* @return createTermId Identification number of the term when the dispute was created
*/
function getDispute(uint256 _disputeId) external view
returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId);
/**
* @dev Tell information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return draftTerm Term from which the requested round can be drafted
* @return delayedTerms Number of terms the given round was delayed based on its requested draft term id
* @return guardiansNumber Number of guardians requested for the round
* @return selectedGuardians Number of guardians already selected for the requested round
* @return settledPenalties Whether or not penalties have been settled for the requested round
* @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round
* @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round
* @return state Adjudication state of the requested round
*/
function getRound(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 draftTerm,
uint64 delayedTerms,
uint64 guardiansNumber,
uint64 selectedGuardians,
uint256 guardianFees,
bool settledPenalties,
uint256 collectedTokens,
uint64 coherentGuardians,
AdjudicationState state
);
/**
* @dev Tell appeal-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return maker Address of the account appealing the given round
* @return appealedRuling Ruling confirmed by the appealer of the given round
* @return taker Address of the account confirming the appeal of the given round
* @return opposedRuling Ruling confirmed by the appeal taker of the given round
*/
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling);
/**
* @dev Tell information related to the next round due to an appeal of a certain round given.
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round requesting the appeal details of
* @return nextRoundStartTerm Term ID from which the next round will start
* @return nextRoundGuardiansNumber Guardians number for the next round
* @return newDisputeState New state for the dispute associated to the given round after the appeal
* @return feeToken ERC20 token used for the next round fees
* @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round
* @return totalFees Total amount of fees for a regular round at the given term
* @return appealDeposit Amount to be deposit of fees for a regular round at the given term
* @return confirmAppealDeposit Total amount of fees for a regular round at the given term
*/
function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 nextRoundStartTerm,
uint64 nextRoundGuardiansNumber,
DisputeState newDisputeState,
IERC20 feeToken,
uint256 totalFees,
uint256 guardianFees,
uint256 appealDeposit,
uint256 confirmAppealDeposit
);
/**
* @dev Tell guardian-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @param _guardian Address of the guardian being queried
* @return weight Guardian weight drafted for the requested round
* @return rewarded Whether or not the given guardian was rewarded based on the requested round
*/
function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded);
}
contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL {
string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR";
string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS";
string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET";
string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED";
string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED";
string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE";
string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET";
string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT";
string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH";
address private constant ZERO_ADDRESS = address(0);
/**
* @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules
*/
struct Governor {
address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules
address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system
address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system
}
/**
* @dev Module information
*/
struct Module {
bytes32 id; // ID associated to a module
bool disabled; // Whether the module is disabled
}
// Governor addresses of the system
Governor private governor;
// List of current modules registered for the system indexed by ID
mapping (bytes32 => address) internal currentModules;
// List of all historical modules registered for the system indexed by address
mapping (address => Module) internal allModules;
// List of custom function targets indexed by signature
mapping (bytes4 => address) internal customFunctions;
event ModuleSet(bytes32 id, address addr);
event ModuleEnabled(bytes32 id, address addr);
event ModuleDisabled(bytes32 id, address addr);
event CustomFunctionSet(bytes4 signature, address target);
event FundsGovernorChanged(address previousGovernor, address currentGovernor);
event ConfigGovernorChanged(address previousGovernor, address currentGovernor);
event ModulesGovernorChanged(address previousGovernor, address currentGovernor);
/**
* @dev Ensure the msg.sender is the funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyConfigGovernor {
require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyModulesGovernor {
require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the given dispute manager is active
*/
modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) {
require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
* @param _governors Array containing:
* 0. _fundsGovernor Address of the funds governor
* 1. _configGovernor Address of the config governor
* 2. _modulesGovernor Address of the modules governor
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
uint64[2] memory _termParams,
address[3] memory _governors,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
CourtClock(_termParams)
CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance)
{
_setFundsGovernor(_governors[0]);
_setConfigGovernor(_governors[1]);
_setModulesGovernor(_governors[2]);
}
/**
* @dev Fallback function allows to forward calls to a specific address in case it was previously registered
* Note the sender will be always the controller in case it is forwarded
*/
function () external payable {
address target = customFunctions[msg.sig];
require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET);
// solium-disable-next-line security/no-call-value
(bool success,) = address(target).call.value(msg.value)(msg.data);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
let result := success
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @notice Change Court configuration params
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function setConfig(
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] calldata _fees,
uint64[5] calldata _roundStateDurations,
uint16[2] calldata _pcts,
uint64[4] calldata _roundParams,
uint256[2] calldata _appealCollateralParams,
uint256 _minActiveBalance
)
external
onlyConfigGovernor
{
uint64 currentTermId = _ensureCurrentTerm();
_setConfig(
currentTermId,
_fromTermId,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @notice Delay the Court start time to `_newFirstTermStartTime`
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor {
_delayStartTime(_newFirstTermStartTime);
}
/**
* @notice Change funds governor address to `_newFundsGovernor`
* @param _newFundsGovernor Address of the new funds governor to be set
*/
function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor {
require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setFundsGovernor(_newFundsGovernor);
}
/**
* @notice Change config governor address to `_newConfigGovernor`
* @param _newConfigGovernor Address of the new config governor to be set
*/
function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor {
require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setConfigGovernor(_newConfigGovernor);
}
/**
* @notice Change modules governor address to `_newModulesGovernor`
* @param _newModulesGovernor Address of the new governor to be set
*/
function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor {
require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setModulesGovernor(_newModulesGovernor);
}
/**
* @notice Remove the funds governor. Set the funds governor to the zero address.
* @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore
*/
function ejectFundsGovernor() external onlyFundsGovernor {
_setFundsGovernor(ZERO_ADDRESS);
}
/**
* @notice Remove the modules governor. Set the modules governor to the zero address.
* @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore
*/
function ejectModulesGovernor() external onlyModulesGovernor {
_setModulesGovernor(ZERO_ADDRESS);
}
/**
* @notice Grant `_id` role to `_who`
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function grant(bytes32 _id, address _who) external onlyConfigGovernor {
_grant(_id, _who);
}
/**
* @notice Revoke `_id` role from `_who`
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function revoke(bytes32 _id, address _who) external onlyConfigGovernor {
_revoke(_id, _who);
}
/**
* @notice Freeze `_id` role
* @param _id ID of the role to be frozen
*/
function freeze(bytes32 _id) external onlyConfigGovernor {
_freeze(_id);
}
/**
* @notice Enact a bulk list of ACL operations
*/
function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor {
_bulk(_op, _id, _who);
}
/**
* @notice Set module `_id` to `_addr`
* @param _id ID of the module to be set
* @param _addr Address of the module to be set
*/
function setModule(bytes32 _id, address _addr) external onlyModulesGovernor {
_setModule(_id, _addr);
}
/**
* @notice Set and link many modules at once
* @param _newModuleIds List of IDs of the new modules to be set
* @param _newModuleAddresses List of addresses of the new modules to be set
* @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set
* @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set
*/
function setModules(
bytes32[] calldata _newModuleIds,
address[] calldata _newModuleAddresses,
bytes32[] calldata _newModuleLinks,
address[] calldata _currentModulesToBeSynced
)
external
onlyModulesGovernor
{
// We only care about the modules being set, links are optional
require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH);
// First set the addresses of the new modules or the modules to be updated
for (uint256 i = 0; i < _newModuleIds.length; i++) {
_setModule(_newModuleIds[i], _newModuleAddresses[i]);
}
// Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies)
_syncModuleLinks(_newModuleAddresses, _newModuleLinks);
// Finally sync the links of the existing modules to be synced to the new modules being set
_syncModuleLinks(_currentModulesToBeSynced, _newModuleIds);
}
/**
* @notice Sync modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules included in the sync
*/
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet)
external
onlyModulesGovernor
{
require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH);
_syncModuleLinks(_modulesToBeSynced, _idsToBeSet);
}
/**
* @notice Disable module `_addr`
* @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule`
* @param _addr Address of the module to be disabled
*/
function disableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED);
module.disabled = true;
emit ModuleDisabled(module.id, _addr);
}
/**
* @notice Enable module `_addr`
* @param _addr Address of the module to be enabled
*/
function enableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(module.disabled, ERROR_MODULE_ALREADY_ENABLED);
module.disabled = false;
emit ModuleEnabled(module.id, _addr);
}
/**
* @notice Set custom function `_sig` for `_target`
* @param _sig Signature of the function to be set
* @param _target Address of the target implementation to be registered for the given signature
*/
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor {
customFunctions[_sig] = _target;
emit CustomFunctionSet(_sig, _target);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getConfigAt(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getDraftConfig(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getMinActiveBalance(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the address of the funds governor
* @return Address of the funds governor
*/
function getFundsGovernor() external view returns (address) {
return governor.funds;
}
/**
* @dev Tell the address of the config governor
* @return Address of the config governor
*/
function getConfigGovernor() external view returns (address) {
return governor.config;
}
/**
* @dev Tell the address of the modules governor
* @return Address of the modules governor
*/
function getModulesGovernor() external view returns (address) {
return governor.modules;
}
/**
* @dev Tell if a given module is active
* @param _id ID of the module to be checked
* @param _addr Address of the module to be checked
* @return True if the given module address has the requested ID and is enabled
*/
function isActive(bytes32 _id, address _addr) external view returns (bool) {
Module storage module = allModules[_addr];
return module.id == _id && !module.disabled;
}
/**
* @dev Tell the current ID and disable status of a module based on a given address
* @param _addr Address of the requested module
* @return id ID of the module being queried
* @return disabled Whether the module has been disabled
*/
function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) {
Module storage module = allModules[_addr];
id = module.id;
disabled = module.disabled;
}
/**
* @dev Tell the current address and disable status of a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function getModule(bytes32 _id) external view returns (address addr, bool disabled) {
return _getModule(_id);
}
/**
* @dev Tell the information for the current DisputeManager module
* @return addr Current address of the DisputeManager module
* @return disabled Whether the module has been disabled
*/
function getDisputeManager() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_DISPUTE_MANAGER);
}
/**
* @dev Tell the information for the current GuardiansRegistry module
* @return addr Current address of the GuardiansRegistry module
* @return disabled Whether the module has been disabled
*/
function getGuardiansRegistry() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_GUARDIANS_REGISTRY);
}
/**
* @dev Tell the information for the current Voting module
* @return addr Current address of the Voting module
* @return disabled Whether the module has been disabled
*/
function getVoting() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_VOTING);
}
/**
* @dev Tell the information for the current PaymentsBook module
* @return addr Current address of the PaymentsBook module
* @return disabled Whether the module has been disabled
*/
function getPaymentsBook() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_PAYMENTS_BOOK);
}
/**
* @dev Tell the information for the current Treasury module
* @return addr Current address of the Treasury module
* @return disabled Whether the module has been disabled
*/
function getTreasury() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_TREASURY);
}
/**
* @dev Tell the target registered for a custom function
* @param _sig Signature of the function being queried
* @return Address of the target where the function call will be forwarded
*/
function getCustomFunction(bytes4 _sig) external view returns (address) {
return customFunctions[_sig];
}
/**
* @dev Internal function to set the address of the funds governor
* @param _newFundsGovernor Address of the new config governor to be set
*/
function _setFundsGovernor(address _newFundsGovernor) internal {
emit FundsGovernorChanged(governor.funds, _newFundsGovernor);
governor.funds = _newFundsGovernor;
}
/**
* @dev Internal function to set the address of the config governor
* @param _newConfigGovernor Address of the new config governor to be set
*/
function _setConfigGovernor(address _newConfigGovernor) internal {
emit ConfigGovernorChanged(governor.config, _newConfigGovernor);
governor.config = _newConfigGovernor;
}
/**
* @dev Internal function to set the address of the modules governor
* @param _newModulesGovernor Address of the new modules governor to be set
*/
function _setModulesGovernor(address _newModulesGovernor) internal {
emit ModulesGovernorChanged(governor.modules, _newModulesGovernor);
governor.modules = _newModulesGovernor;
}
/**
* @dev Internal function to set an address as the current implementation for a module
* Note that the disabled condition is not affected, if the module was not set before it will be enabled by default
* @param _id Id of the module to be set
* @param _addr Address of the module to be set
*/
function _setModule(bytes32 _id, address _addr) internal {
require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT);
currentModules[_id] = _addr;
allModules[_addr].id = _id;
emit ModuleSet(_id, _addr);
}
/**
* @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules to be linked
*/
function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal {
address[] memory addressesToBeSet = new address[](_idsToBeSet.length);
// Load the addresses associated with the requested module ids
for (uint256 i = 0; i < _idsToBeSet.length; i++) {
address moduleAddress = _getModuleAddress(_idsToBeSet[i]);
Module storage module = allModules[moduleAddress];
_ensureModuleExists(module);
addressesToBeSet[i] = moduleAddress;
}
// Update the links of all the requested modules
for (uint256 j = 0; j < _modulesToBeSynced.length; j++) {
IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet);
}
}
/**
* @dev Internal function to notify when a term has been transitioned
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal {
_ensureTermConfig(_termId);
}
/**
* @dev Internal function to check if a module was set
* @param _module Module to be checked
*/
function _ensureModuleExists(Module storage _module) internal view {
require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET);
}
/**
* @dev Internal function to tell the information for a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) {
addr = _getModuleAddress(_id);
disabled = _isModuleDisabled(addr);
}
/**
* @dev Tell the current address for a module by ID
* @param _id ID of the module being queried
* @return Current address of the requested module
*/
function _getModuleAddress(bytes32 _id) internal view returns (address) {
return currentModules[_id];
}
/**
* @dev Tell whether a module is disabled
* @param _addr Address of the module being queried
* @return True if the module is disabled, false otherwise
*/
function _isModuleDisabled(address _addr) internal view returns (bool) {
return allModules[_addr].disabled;
}
}
contract ConfigConsumer is CourtConfigData {
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig);
/**
* @dev Internal function to get the Court config for a certain term
* @param _termId Identification number of the term querying the Court config of
* @return Court config for the given term
*/
function _getConfigAt(uint64 _termId) internal view returns (Config memory) {
(IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance) = _courtConfig().getConfig(_termId);
Config memory config;
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _roundParams[2],
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
return config;
}
/**
* @dev Internal function to get the draft config for a given term
* @param _termId Identification number of the term querying the draft config of
* @return Draft config for the given term
*/
function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of guardian tokens that can be activated
*/
function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) {
return _courtConfig().getMinActiveBalance(_termId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVotingOwner {
/**
* @dev Ensure votes can be committed for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
*/
function ensureCanCommit(uint256 _voteId) external;
/**
* @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
*/
function ensureCanCommit(uint256 _voteId, address _voter) external;
/**
* @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
* @return Weight of the requested guardian for the requested vote instance
*/
function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVoting {
/**
* @dev Create a new vote instance
* @dev This function can only be called by the CRVoting owner
* @param _voteId ID of the new vote instance to be created
* @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created
*/
function createVote(uint256 _voteId, uint8 _possibleOutcomes) external;
/**
* @dev Get the winning outcome of a vote instance
* @param _voteId ID of the vote instance querying the winning outcome of
* @return Winning outcome of the given vote instance or refused in case it's missing
*/
function getWinningOutcome(uint256 _voteId) external view returns (uint8);
/**
* @dev Get the tally of an outcome for a certain vote instance
* @param _voteId ID of the vote instance querying the tally of
* @param _outcome Outcome querying the tally of
* @return Tally of the outcome being queried for the given vote instance
*/
function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256);
/**
* @dev Tell whether an outcome is valid for a given vote instance or not
* @param _voteId ID of the vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise
*/
function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool);
/**
* @dev Get the outcome voted by a voter for a certain vote instance
* @param _voteId ID of the vote instance querying the outcome of
* @param _voter Address of the voter querying the outcome of
* @return Outcome of the voter for the given vote instance
*/
function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8);
/**
* @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome
* @param _outcome Outcome to query if the given voter voted in favor of
* @param _voter Address of the voter to query if voted in favor of the given outcome
* @return True if the given voter voted in favor of the given outcome, false otherwise
*/
function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool);
/**
* @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to be checked
* @param _outcome Outcome to filter the list of voters of
* @param _voters List of addresses of the voters to be filtered
* @return List of results to tell whether a voter voted in favor of the given outcome or not
*/
function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ITreasury {
/**
* @dev Assign a certain amount of tokens to an account
* @param _token ERC20 token to be assigned
* @param _to Address of the recipient that will be assigned the tokens to
* @param _amount Amount of tokens to be assigned to the recipient
*/
function assign(IERC20 _token, address _to, uint256 _amount) external;
/**
* @dev Withdraw a certain amount of tokens
* @param _token ERC20 token to be withdrawn
* @param _from Address withdrawing the tokens from
* @param _to Address of the recipient that will receive the tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external;
}
/*
* SPDX-License-Identifier: MIT
*/
interface IPaymentsBook {
/**
* @dev Pay an amount of tokens
* @param _token Address of the token being paid
* @param _amount Amount of tokens being paid
* @param _payer Address paying on behalf of
* @param _data Optional data
*/
function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable;
}
contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer {
string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET";
string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT";
string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT";
string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED";
string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER";
string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR";
string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING";
string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR";
string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR";
// Address of the controller
Controller public controller;
// List of modules linked indexed by ID
mapping (bytes32 => address) public linkedModules;
event ModuleLinked(bytes32 id, address addr);
/**
* @dev Ensure the msg.sender is the controller's config governor
*/
modifier onlyConfigGovernor {
require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the controller
*/
modifier onlyController() {
require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER);
_;
}
/**
* @dev Ensure the msg.sender is an active DisputeManager module
*/
modifier onlyActiveDisputeManager() {
require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is the current DisputeManager module
*/
modifier onlyCurrentDisputeManager() {
(address addr, bool disabled) = controller.getDisputeManager();
require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER);
require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is an active Voting module
*/
modifier onlyActiveVoting() {
require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING);
_;
}
/**
* @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
modifier authenticateSender(address _user) {
_authenticateSender(_user);
_;
}
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) public {
require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT);
controller = _controller;
}
/**
* @notice Update the implementation links of a list of modules
* @dev The controller is expected to ensure the given addresses are correct modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController {
require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT);
for (uint256 i = 0; i < _ids.length; i++) {
linkedModules[_ids[i]] = _addresses[i];
emit ModuleLinked(_ids[i], _addresses[i]);
}
}
/**
* @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not
* @return Identification number of the current Court term
*/
function _ensureCurrentTerm() internal returns (uint64) {
return _clock().ensureCurrentTerm();
}
/**
* @dev Internal function to fetch the last ensured term ID of the Court
* @return Identification number of the last ensured term
*/
function _getLastEnsuredTermId() internal view returns (uint64) {
return _clock().getLastEnsuredTermId();
}
/**
* @dev Internal function to tell the current term identification number
* @return Identification number of the current term
*/
function _getCurrentTermId() internal view returns (uint64) {
return _clock().getCurrentTermId();
}
/**
* @dev Internal function to fetch the controller's config governor
* @return Address of the controller's config governor
*/
function _configGovernor() internal view returns (address) {
return controller.getConfigGovernor();
}
/**
* @dev Internal function to fetch the address of the DisputeManager module
* @return Address of the DisputeManager module
*/
function _disputeManager() internal view returns (IDisputeManager) {
return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER));
}
/**
* @dev Internal function to fetch the address of the GuardianRegistry module implementation
* @return Address of the GuardianRegistry module implementation
*/
function _guardiansRegistry() internal view returns (IGuardiansRegistry) {
return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY));
}
/**
* @dev Internal function to fetch the address of the Voting module implementation
* @return Address of the Voting module implementation
*/
function _voting() internal view returns (ICRVoting) {
return ICRVoting(_getLinkedModule(MODULE_ID_VOTING));
}
/**
* @dev Internal function to fetch the address of the PaymentsBook module implementation
* @return Address of the PaymentsBook module implementation
*/
function _paymentsBook() internal view returns (IPaymentsBook) {
return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK));
}
/**
* @dev Internal function to fetch the address of the Treasury module implementation
* @return Address of the Treasury module implementation
*/
function _treasury() internal view returns (ITreasury) {
return ITreasury(_getLinkedModule(MODULE_ID_TREASURY));
}
/**
* @dev Internal function to tell the address linked for a module based on a given ID
* @param _id ID of the module being queried
* @return Linked address of the requested module
*/
function _getLinkedModule(bytes32 _id) internal view returns (address) {
address module = linkedModules[_id];
require(module != address(0), ERROR_MODULE_NOT_SET);
return module;
}
/**
* @dev Internal function to fetch the address of the Clock module from the controller
* @return Address of the Clock module
*/
function _clock() internal view returns (IClock) {
return IClock(controller);
}
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig) {
return IConfig(controller);
}
/**
* @dev Ensure that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
function _authenticateSender(address _user) internal view {
require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED);
}
/**
* @dev Tell whether the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
* @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise
*/
function _isSenderAllowed(address _user) internal view returns (bool) {
return msg.sender == _user || _hasRole(msg.sender);
}
/**
* @dev Tell whether an address holds the required permission to access the requested functionality
* @param _addr Address being checked
* @return True if the given address has the required permission to access the requested functionality, false otherwise
*/
function _hasRole(address _addr) internal view returns (bool) {
bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig));
return controller.hasRole(_addr, roleId);
}
}
contract ControlledRecoverable is Controlled {
using SafeERC20 for IERC20;
string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR";
string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS";
string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED";
event RecoverFunds(address token, address recipient, uint256 balance);
/**
* @dev Ensure the msg.sender is the controller's funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR);
_;
}
/**
* @notice Transfer all `_token` tokens to `_to`
* @param _token Address of the token to be recovered
* @param _to Address of the recipient that will be receive all the funds of the requested token
*/
function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor {
uint256 balance;
if (_token == address(0)) {
balance = address(this).balance;
require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
} else {
balance = IERC20(_token).balanceOf(address(this));
require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS);
// No need to verify _token to be a contract as we have already checked the balance
require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
}
emit RecoverFunds(_token, _to, balance);
}
}
contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using PctHelpers for uint256;
using HexSumTree for HexSumTree.Tree;
using GuardiansTreeSortition for HexSumTree.Tree;
string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT";
string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT";
string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT";
string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT";
string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN";
string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN";
string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN";
string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE";
string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED";
string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED";
string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT";
string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED";
string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK";
string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION";
string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION";
string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT";
string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED";
string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK";
// Address that will be used to burn guardian tokens
address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD);
// Maximum number of sortition iterations allowed per draft call
uint256 internal constant MAX_DRAFT_ITERATIONS = 10;
// "ERC20-lite" interface to provide help for tooling
string public constant name = "Court Staked Aragon Network Token";
string public constant symbol = "sANT";
uint8 public constant decimals = 18;
/**
* @dev Guardians have three kind of balances, these are:
* - active: tokens activated for the Court that can be locked in case the guardian is drafted
* - locked: amount of active tokens that are locked for a draft
* - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time
*
* Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others
* are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians'
* active balances cannot be affected during the current Court term, if guardians want to deactivate some of
* their active tokens, their balance will be updated for the following term, and they won't be allowed to
* withdraw them until the current term has ended.
*
* Note that even though guardians balances are stored separately, all the balances are held by this contract.
*/
struct Guardian {
uint256 id; // Key in the guardians tree used for drafting
uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts
uint256 availableBalance; // Available tokens that can be withdrawn at any time
uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked
ActivationLocks activationLocks; // Guardian's activation locks
DeactivationRequest deactivationRequest; // Guardian's pending deactivation request
}
/**
* @dev Guardians can define lock managers to control their minimum active balance in the registry
*/
struct ActivationLocks {
uint256 total; // Total amount of active balance locked
mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager
}
/**
* @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some
* of their tokens, the tree will always be updated for the following term, and they won't be able to
* withdraw the requested amount until the current term has finished. Thus, we need to keep track the term
* when a token deactivation was requested and its corresponding amount.
*/
struct DeactivationRequest {
uint256 amount; // Amount requested for deactivation
uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens
}
/**
* @dev Internal struct to wrap all the params required to perform guardians drafting
*/
struct DraftParams {
bytes32 termRandomness; // Randomness seed to be used for the draft
uint256 disputeId; // ID of the dispute being drafted
uint64 termId; // Term ID of the dispute's draft term
uint256 selectedGuardians; // Number of guardians already selected for the draft
uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft
uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted
uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian
uint256 iteration; // Sortition iteration number
}
// Maximum amount of total active balance that can be held in the registry
uint256 public totalActiveBalanceLimit;
// Guardian ERC20 token
IERC20 public guardiansToken;
// Mapping of guardian data indexed by address
mapping (address => Guardian) internal guardiansByAddress;
// Mapping of guardian addresses indexed by id
mapping (uint256 => address) internal guardiansAddressById;
// Tree to store guardians active balance by term for the drafting process
HexSumTree.Tree internal tree;
event Staked(address indexed guardian, uint256 amount, uint256 total);
event Unstaked(address indexed guardian, uint256 amount, uint256 total);
event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount);
event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount);
event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId);
event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId);
event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total);
event GuardianBalanceLocked(address indexed guardian, uint256 amount);
event GuardianBalanceUnlocked(address indexed guardian, uint256 amount);
event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId);
event GuardianTokensAssigned(address indexed guardian, uint256 amount);
event GuardianTokensBurned(uint256 amount);
event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId);
event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit);
/**
* @dev Constructor function
* @param _controller Address of the controller
* @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry
* @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry
*/
constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public {
require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT);
guardiansToken = _guardiansToken;
_setTotalActiveBalanceLimit(_totalActiveBalanceLimit);
tree.init();
// First tree item is an empty guardian
assert(tree.insert(0, 0) == 0);
}
/**
* @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian to stake tokens to
* @param _amount Amount of tokens to be staked
*/
function stake(address _guardian, uint256 _amount) external {
_stake(_guardian, _amount);
}
/**
* @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian`
* @param _guardian Address of the guardian to unstake tokens from
* @param _amount Amount of tokens to be unstaked
*/
function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_unstake(_guardian, _amount);
}
/**
* @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian activating the tokens for
* @param _amount Amount of guardian tokens to be activated for the next term
*/
function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_activate(_guardian, _amount);
}
/**
* @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian deactivating the tokens for
* @param _amount Amount of guardian tokens to be deactivated for the next term
*/
function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_deactivate(_guardian, _amount);
}
/**
* @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian staking and activating tokens for
* @param _amount Amount of tokens to be staked and activated
*/
function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_stake(_guardian, _amount);
_activate(_guardian, _amount);
}
/**
* @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance
* @param _guardian Address of the guardian locking the activation for
* @param _lockManager Address of the lock manager that will control the lock
* @param _amount Amount of active tokens to be locked
*/
function lockActivation(address _guardian, address _lockManager, uint256 _amount) external {
// Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself
bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian);
// Make sure that the given lock manager is allowed
require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED);
_lockActivation(_guardian, _lockManager, _amount);
}
/**
* @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance
* @param _guardian Address of the guardian unlocking the active balance of
* @param _lockManager Address of the lock manager controlling the lock
* @param _amount Amount of active tokens to be unlocked
* @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately
*/
function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
uint256 lockedAmount = activationLocks.lockedBy[_lockManager];
require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION);
uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount;
require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT);
// Always allow the lock manager to unlock
bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock);
require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION);
uint256 newLockedAmount = lockedAmount.sub(amountToUnlock);
uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock);
activationLocks.total = newTotalLocked;
activationLocks.lockedBy[_lockManager] = newLockedAmount;
emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked);
// In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it
if (_requestDeactivation) {
_authenticateSender(_guardian);
_deactivate(_guardian, _amount);
}
}
/**
* @notice Process a token deactivation requested for `_guardian` if there is any
* @param _guardian Address of the guardian to process the deactivation request of
*/
function processDeactivationRequest(address _guardian) external {
uint64 termId = _ensureCurrentTerm();
_processDeactivationRequest(_guardian, termId);
}
/**
* @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian`
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager {
if (_amount > 0) {
_updateAvailableBalanceOf(_guardian, _amount, true);
emit GuardianTokensAssigned(_guardian, _amount);
}
}
/**
* @notice Burn `@tokenAmount(self.token(), _amount)`
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external onlyActiveDisputeManager {
if (_amount > 0) {
_updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true);
emit GuardianTokensBurned(_amount);
}
}
/**
* @notice Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) {
DraftParams memory draftParams = _buildDraftParams(_params);
guardians = new address[](draftParams.batchRequestedGuardians);
// Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus,
// we compute several sortitions until all the requested guardians are selected. To guarantee a different set of
// guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition.
// Note that we are capping the number of iterations to avoid an OOG error, which means that this function could
// return less guardians than the requested number.
for (draftParams.iteration = 0;
length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS;
draftParams.iteration++
) {
(uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams);
for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) {
// We assume the selected guardians are registered in the registry, we are not checking their addresses exist
address guardianAddress = guardiansAddressById[guardianIds[i]];
Guardian storage guardian = guardiansByAddress[guardianAddress];
// Compute new locked balance for a guardian based on the penalty applied when being drafted
uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount);
// Check if there is any deactivation requests for the next term. Drafts are always computed for the current term
// but we have to make sure we are locking an amount that will exist in the next term.
uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1);
// Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise.
uint256 currentActiveBalance = activeBalances[i];
if (currentActiveBalance >= newLockedBalance) {
// Check if the amount of active tokens for the next term is enough to lock the required amount for
// the draft. Otherwise, reduce the requested deactivation amount of the next term.
// Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath
uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount);
if (nextTermActiveBalance < newLockedBalance) {
// No need for SafeMath: we already checked values above
_reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId);
}
// Update the current active locked balance of the guardian
guardian.lockedBalance = newLockedBalance;
guardians[length++] = guardianAddress;
emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount);
}
}
}
}
/**
* @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the
* corresponding locked balances of those guardians that are set to be slashed.
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
onlyActiveDisputeManager
returns (uint256)
{
require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH);
require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH);
uint64 nextTermId = _termId + 1;
uint256 collectedTokens;
for (uint256 i = 0; i < _guardians.length; i++) {
uint256 lockedAmount = _lockedAmounts[i];
address guardianAddress = _guardians[i];
Guardian storage guardian = guardiansByAddress[guardianAddress];
guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount);
// Slash guardian if requested. Note that there's no need to check if there was a deactivation
// request since we're working with already locked balances.
if (_rewardedGuardians[i]) {
emit GuardianBalanceUnlocked(guardianAddress, lockedAmount);
} else {
collectedTokens = collectedTokens.add(lockedAmount);
tree.update(guardian.id, nextTermId, lockedAmount, false);
emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId);
}
}
return collectedTokens;
}
/**
* @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`.
* @dev This function tries to decrease the active balance of a guardian for the next term based on the requested
* amount. It can be seen as a way to early-slash a guardian's active balance.
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) {
if (_amount == 0) {
return true;
}
uint64 nextTermId = _termId + 1;
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian);
uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId);
// Check if the guardian has enough unlocked tokens to collect the requested amount
// Note that we're also considering the deactivation request if there is any
uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount);
if (_amount > totalUnlockedActiveBalance) {
return false;
}
// Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of
// the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect
// of a guardian deliberately voting in a final round, while drafts occur randomly.
if (_amount > unlockedActiveBalance) {
// No need for SafeMath: amounts were already checked above
uint256 amountToReduce = _amount - unlockedActiveBalance;
_reduceDeactivationRequest(_guardian, amountToReduce, _termId);
}
tree.update(guardian.id, nextTermId, _amount, false);
emit GuardianTokensCollected(_guardian, _amount, nextTermId);
return true;
}
/**
* @notice Lock `_guardian`'s withdrawals until term #`_termId`
* @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager {
Guardian storage guardian = guardiansByAddress[_guardian];
guardian.withdrawalsLockTermId = _termId;
}
/**
* @notice Set new limit of total active balance of guardian tokens
* @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens
*/
function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor {
_setTotalActiveBalanceLimit(_totalActiveBalanceLimit);
}
/**
* @dev Tell the total supply of guardian tokens staked
* @return Supply of guardian tokens staked
*/
function totalSupply() external view returns (uint256) {
return guardiansToken.balanceOf(address(this));
}
/**
* @dev Tell the total amount of active guardian tokens
* @return Total amount of active guardian tokens
*/
function totalActiveBalance() external view returns (uint256) {
return tree.getTotal();
}
/**
* @dev Tell the total amount of active guardian tokens for a given term id
* @param _termId Term ID to query on
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) {
return _totalActiveBalanceAt(_termId);
}
/**
* @dev Tell the total balance of tokens held by a guardian
* This includes the active balance, the available balances, and the pending balance for deactivation.
* Note that we don't have to include the locked balances since these represent the amount of active tokens
* that are locked for drafts, i.e. these are already included in the active balance of the guardian.
* @param _guardian Address of the guardian querying the balance of
* @return Total amount of tokens of a guardian
*/
function balanceOf(address _guardian) external view returns (uint256) {
return _balanceOf(_guardian);
}
/**
* @dev Tell the detailed balance information of a guardian
* @param _guardian Address of the guardian querying the detailed balance information of
* @return active Amount of active tokens of a guardian
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function detailedBalanceOf(address _guardian) external view
returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation)
{
return _detailedBalanceOf(_guardian);
}
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID to query on
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) {
return _activeBalanceOfAt(_guardian, _termId);
}
/**
* @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes
* @param _guardian Address of the guardian querying the unlocked balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) {
Guardian storage guardian = guardiansByAddress[_guardian];
return _currentUnlockedActiveBalanceOf(guardian);
}
/**
* @dev Tell the pending deactivation details for a guardian
* @param _guardian Address of the guardian whose info is requested
* @return amount Amount to be deactivated
* @return availableTermId Term in which the deactivated amount will be available
*/
function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) {
DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest;
return (request.amount, request.availableTermId);
}
/**
* @dev Tell the activation amount locked for a guardian by a lock manager
* @param _guardian Address of the guardian whose info is requested
* @param _lockManager Address of the lock manager querying the lock of
* @return amount Activation amount locked by the lock manager
* @return total Total activation amount locked for the guardian
*/
function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
total = activationLocks.total;
amount = activationLocks.lockedBy[_lockManager];
}
/**
* @dev Tell the withdrawals lock term ID for a guardian
* @param _guardian Address of the guardian whose info is requested
* @return Term ID until which the guardian's withdrawals will be locked
*/
function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) {
return guardiansByAddress[_guardian].withdrawalsLockTermId;
}
/**
* @dev Tell the identification number associated to a guardian address
* @param _guardian Address of the guardian querying the identification number of
* @return Identification number associated to a guardian address, zero in case it wasn't registered yet
*/
function getGuardianId(address _guardian) external view returns (uint256) {
return guardiansByAddress[_guardian].id;
}
/**
* @dev Internal function to activate a given amount of tokens for a guardian.
* This function assumes that the given term is the current term and has already been ensured.
* @param _guardian Address of the guardian to activate tokens
* @param _amount Amount of guardian tokens to be activated
*/
function _activate(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
// Try to clean a previous deactivation request if any
_processDeactivationRequest(_guardian, termId);
uint256 availableBalance = guardiansByAddress[_guardian].availableBalance;
uint256 amountToActivate = _amount == 0 ? availableBalance : _amount;
require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT);
require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT);
uint64 nextTermId = termId + 1;
_checkTotalActiveBalance(nextTermId, amountToActivate);
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 minActiveBalance = _getMinActiveBalance(nextTermId);
if (_existsGuardian(guardian)) {
// Even though we are adding amounts, let's check the new active balance is greater than or equal to the
// minimum active amount. Note that the guardian might have been slashed.
uint256 activeBalance = tree.getItem(guardian.id);
require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN);
tree.update(guardian.id, nextTermId, amountToActivate, true);
} else {
require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN);
guardian.id = tree.insert(nextTermId, amountToActivate);
guardiansAddressById[guardian.id] = _guardian;
}
_updateAvailableBalanceOf(_guardian, amountToActivate, false);
emit GuardianActivated(_guardian, nextTermId, amountToActivate);
}
/**
* @dev Internal function to deactivate a given amount of tokens for a guardian.
* @param _guardian Address of the guardian to deactivate tokens
* @param _amount Amount of guardian tokens to be deactivated for the next term
*/
function _deactivate(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian);
uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount;
require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT);
require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT);
// Check future balance is not below the total activation lock of the guardian
// No need for SafeMath: we already checked values above
uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate;
uint256 totalActivationLock = guardian.activationLocks.total;
require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK);
// Check that the guardian is leaving or that the minimum active balance is met
uint256 minActiveBalance = _getMinActiveBalance(termId);
require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT);
_createDeactivationRequest(_guardian, amountToDeactivate);
}
/**
* @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed
* to process a deactivation request from the next term.
* @param _guardian Address of the guardian to create a token deactivation request for
* @param _amount Amount of guardian tokens requested for deactivation
*/
function _createDeactivationRequest(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
// Try to clean a previous deactivation request if possible
_processDeactivationRequest(_guardian, termId);
uint64 nextTermId = termId + 1;
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
request.amount = request.amount.add(_amount);
request.availableTermId = nextTermId;
tree.update(guardian.id, nextTermId, _amount, false);
emit GuardianDeactivationRequested(_guardian, nextTermId, _amount);
}
/**
* @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount
* to the available balance of the guardian if the term when the deactivation was requested has already finished.
* @param _guardian Address of the guardian to process the deactivation request of
* @param _termId Current term id
*/
function _processDeactivationRequest(address _guardian, uint64 _termId) internal {
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
uint64 deactivationAvailableTermId = request.availableTermId;
// If there is a deactivation request, ensure that the deactivation term has been reached
if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) {
return;
}
uint256 deactivationAmount = request.amount;
// Note that we can use a zeroed term ID to denote void here since we are storing
// the minimum allowed term to deactivate tokens which will always be at least 1.
request.availableTermId = uint64(0);
request.amount = 0;
_updateAvailableBalanceOf(_guardian, deactivationAmount, true);
emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId);
}
/**
* @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request
* cannot be processed for the given term yet.
* @param _guardian Address of the guardian to reduce the deactivation request of
* @param _amount Amount to be reduced from the current deactivation request
* @param _termId Term ID in which the deactivation request is being reduced
*/
function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal {
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
uint256 currentRequestAmount = request.amount;
require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST);
// No need for SafeMath: we already checked values above
uint256 newRequestAmount = currentRequestAmount - _amount;
request.amount = newRequestAmount;
// Move amount back to the tree
tree.update(guardian.id, _termId + 1, _amount, true);
emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId);
}
/**
* @dev Internal function to update the activation locked amount of a guardian
* @param _guardian Guardian to update the activation locked amount of
* @param _lockManager Address of the lock manager controlling the lock
* @param _amount Amount of tokens to be added to the activation locked amount of the guardian
*/
function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
uint256 newTotalLocked = activationLocks.total.add(_amount);
uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount);
activationLocks.total = newTotalLocked;
activationLocks.lockedBy[_lockManager] = newLockedAmount;
emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked);
}
/**
* @dev Internal function to stake an amount of tokens for a guardian
* @param _guardian Address of the guardian to deposit the tokens to
* @param _amount Amount of tokens to be deposited
*/
function _stake(address _guardian, uint256 _amount) internal {
require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT);
_updateAvailableBalanceOf(_guardian, _amount, true);
emit Staked(_guardian, _amount, _balanceOf(_guardian));
require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
/**
* @dev Internal function to unstake an amount of tokens of a guardian
* @param _guardian Address of the guardian to to unstake the tokens of
* @param _amount Amount of tokens to be unstaked
*/
function _unstake(address _guardian, uint256 _amount) internal {
require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT);
// Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure
// the current term this time since deactivation requests always work with future terms, which means that if
// the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here
// to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks.
uint64 lastEnsuredTermId = _getLastEnsuredTermId();
// Check that guardian's withdrawals are not locked
uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId;
require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK);
_processDeactivationRequest(_guardian, lastEnsuredTermId);
_updateAvailableBalanceOf(_guardian, _amount, false);
emit Unstaked(_guardian, _amount, _balanceOf(_guardian));
require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
/**
* @dev Internal function to update the available balance of a guardian
* @param _guardian Guardian to update the available balance of
* @param _amount Amount of tokens to be added to or removed from the available balance of a guardian
* @param _positive True if the given amount should be added, or false to remove it from the available balance
*/
function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal {
// We are not using a require here to avoid reverting in case any of the treasury maths reaches this point
// with a zeroed amount value. Instead, we are doing this validation in the external entry points such as
// stake, unstake, activate, deactivate, among others.
if (_amount == 0) {
return;
}
Guardian storage guardian = guardiansByAddress[_guardian];
if (_positive) {
guardian.availableBalance = guardian.availableBalance.add(_amount);
} else {
require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE);
// No need for SafeMath: we already checked values right above
guardian.availableBalance -= _amount;
}
}
/**
* @dev Internal function to set new limit of total active balance of guardian tokens
* @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens
*/
function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal {
require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT);
emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit);
totalActiveBalanceLimit = _totalActiveBalanceLimit;
}
/**
* @dev Internal function to tell the total balance of tokens held by a guardian
* @param _guardian Address of the guardian querying the total balance of
* @return Total amount of tokens of a guardian
*/
function _balanceOf(address _guardian) internal view returns (uint256) {
(uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian);
return available.add(active).add(pendingDeactivation);
}
/**
* @dev Internal function to tell the detailed balance information of a guardian
* @param _guardian Address of the guardian querying the balance information of
* @return active Amount of active tokens of a guardian
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function _detailedBalanceOf(address _guardian) internal view
returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation)
{
Guardian storage guardian = guardiansByAddress[_guardian];
active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0;
(available, locked, pendingDeactivation) = _getBalances(guardian);
}
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) {
Guardian storage guardian = guardiansByAddress[_guardian];
return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0;
}
/**
* @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes
* It will use the last value, that might be in a future term
* @param _guardian Guardian querying the unlocked active balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) {
return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0;
}
/**
* @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes
* @param _guardian Guardian querying the unlocked active balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) {
uint64 lastEnsuredTermId = _getLastEnsuredTermId();
return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0;
}
/**
* @dev Internal function to check if a guardian was already registered
* @param _guardian Guardian to be checked
* @return True if the given guardian was already registered, false otherwise
*/
function _existsGuardian(Guardian storage _guardian) internal view returns (bool) {
return _guardian.id != 0;
}
/**
* @dev Internal function to get the amount of a deactivation request for a given term id
* @param _guardian Guardian to query the deactivation request amount of
* @param _termId Term ID of the deactivation request to be queried
* @return Amount of the deactivation request for the given term, 0 otherwise
*/
function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) {
DeactivationRequest storage request = _guardian.deactivationRequest;
return request.availableTermId == _termId ? request.amount : 0;
}
/**
* @dev Internal function to tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) {
// This function will return always the same values, the only difference remains on gas costs. In case we look for a
// recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint.
// Otherwise, a binary search is computed.
bool recent = _termId >= _getLastEnsuredTermId();
return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId);
}
/**
* @dev Internal function to check if its possible to add a given new amount to the registry or not
* @param _termId Term ID when the new amount will be added
* @param _amount Amount of tokens willing to be added to the registry
*/
function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view {
uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId);
uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount);
require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED);
}
/**
* @dev Tell the local balance information of a guardian (that is not on the tree)
* @param _guardian Address of the guardian querying the balance information of
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) {
available = _guardian.availableBalance;
locked = _guardian.lockedBalance;
pendingDeactivation = _guardian.deactivationRequest.amount;
}
/**
* @dev Internal function to search guardians in the tree based on certain search restrictions
* @param _params Draft params to be used for the guardians search
* @return ids List of guardian ids obtained based on the requested search
* @return activeBalances List of active balances for each guardian obtained based on the requested search
*/
function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) {
(ids, activeBalances) = tree.batchedRandomSearch(
_params.termRandomness,
_params.disputeId,
_params.termId,
_params.selectedGuardians,
_params.batchRequestedGuardians,
_params.roundRequestedGuardians,
_params.iteration
);
}
/**
* @dev Private function to parse a certain set given of draft params
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return Draft params object parsed
*/
function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) {
uint64 termId = uint64(_params[2]);
uint256 minActiveBalance = _getMinActiveBalance(termId);
return DraftParams({
termRandomness: bytes32(_params[0]),
disputeId: _params[1],
termId: termId,
selectedGuardians: _params[3],
batchRequestedGuardians: _params[4],
roundRequestedGuardians: _params[5],
draftLockAmount: minActiveBalance.pct(uint16(_params[6])),
iteration: 0
});
}
}
|
Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree/
|
function getTotal(Tree storage self) internal view returns (uint256) {
uint256 rootLevel = getHeight(self);
return getNode(self, rootLevel, BASE_KEY);
}
| 91,545 |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./HugoNFTAbstractImpl.sol";
abstract contract HugoNFTMinter is ERC721, HugoNFTAbstractImpl {
event Mint(address indexed to, uint256 indexed tokenId, string name, string description);
event ChangeName(uint256 indexed tokenId, string name);
event ChangeDescription(uint256 indexed tokenId, string description);
/**
* @dev Mints a new auto-generative NFT with a seed for a `to` address.
*
* Seed is a an array of traits (more precisely, trait ids) for each attribute
* of the NFT. The function is intended to be called by an NFT shop or owner
* for a give away program.
*
* Concerning seed validation and requirements for it inner structure, see https://github.com/SabaunT/hugo-nft/blob/master/contracts/HugoNFTStorage.sol#L8-L13
* and {HugoNFTMinter-_isValidSeed} with {HugoNFTMinter-_isNewSeed}.
*
* Returns id of the newly generated NFT.
*
* Requirements:
* - `msg.sender` should have {HugoNFTStorage-MINTER_ROLE}
* - `seed` should be valid
* - `name` and `description` must fit bytes length requirements
*/
function mint(
address to,
uint256[] calldata seed,
string calldata name,
string calldata description
)
external
override(AbstractHugoNFT)
onlyRole(MINTER_ROLE)
returns (uint256 newTokenId)
{
require(
_getGeneratedHugoAmount() < generatedHugoCap,
"HugoNFT::supply cap was reached"
);
require(_isValidSeed(seed), "HugoNFT::seed is invalid");
// not to call twice
bytes32 seedHash = _getSeedHash(seed);
require(_isNewSeed(seedHash), "HugoNFT::seed is used");
require(
bytes(name).length > 0 && bytes(name).length <= 75,
"HugoNFT::invalid NFT name length"
);
require(
bytes(description).length > 0 && bytes(description).length <= 300,
"HugoNFT::invalid NFT description length"
);
newTokenId = _getNewIdForGeneratedHugo();
super._safeMint(to, newTokenId);
totalSupply += 1;
uint256[] storage tIdsOfA = _tokenIdsOfAccount[to];
uint256 idInArrayOfIds = tIdsOfA.length;
tIdsOfA.push(newTokenId);
_NFTs[newTokenId] = NFT(newTokenId, name, description, seed, "", idInArrayOfIds);
_isUsedSeed[seedHash] = true;
emit Mint(to, newTokenId, name, description);
return newTokenId;
}
/**
* @dev Mints a new exclusive NFT for a `to` address.
*
* Mints an exclusive NFT, whose IPFS CID is defined under `cid` string.
* Doesn't require any seeds.
*
* Returns id of the newly generated NFT.
*
* Requirements:
* - `msg.sender` should have {HugoNFTStorage-MINTER_ROLE}
* - `cid` should have length equal to {HugoNFTStorage-IPFS_CID_BYTES_LENGTH}
* - `name` and `description` must fit bytes length requirements
*/
function mintExclusive(
address to,
string calldata name,
string calldata description,
string calldata cid
)
external
override(AbstractHugoNFT)
onlyRole(MINTER_ROLE)
returns (uint256 newTokenId)
{
require(
bytes(name).length > 0 && bytes(name).length <= 75,
"HugoNFT::invalid NFT name length"
);
require(
bytes(description).length > 0 && bytes(description).length <= 300,
"HugoNFT::invalid NFT description length"
);
require(
bytes(cid).length == IPFS_CID_BYTES_LENGTH,
"HugoNFT::invalid ipfs CID length"
);
newTokenId = _getNewIdForExclusiveHugo();
super._safeMint(to, newTokenId);
totalSupply += 1;
exclusiveNFTsAmount += 1;
uint256[] storage tIdsOfA = _tokenIdsOfAccount[to];
uint256 idInArrayOfIds = tIdsOfA.length;
tIdsOfA.push(newTokenId);
_NFTs[newTokenId] = NFT(newTokenId, name, description, new uint256[](0), cid, idInArrayOfIds);
emit Mint(to, newTokenId, name, description);
return newTokenId;
}
/**
* @dev Changes name of the NFT with provided tokenId.
*
* Requirements:
* - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role
* - `tokenId` should be an Id of existing NFT
* - `name` shouldn't be empty or larger than 75 bytes
*/
function changeNFTName(uint256 tokenId, string calldata name)
external
override(AbstractHugoNFT)
onlyRole(NFT_ADMIN_ROLE)
{
require(_tokenExists(tokenId), "HugoNFT::nft with such id doesn't exist");
require(
bytes(name).length > 0 && bytes(name).length <= 75,
"HugoNFT::invalid NFT name length"
);
_NFTs[tokenId].name = name;
emit ChangeName(tokenId, name);
}
/**
* @dev Changes description of the NFT with provided tokenId.
*
* Requirements:
* - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role
* - `tokenId` should be an Id of existing NFT
* - `description` shouldn't be empty or larger than 300 bytes
*/
function changeNFTDescription(uint256 tokenId, string calldata description)
external
override(AbstractHugoNFT)
onlyRole(NFT_ADMIN_ROLE)
{
require(_tokenExists(tokenId), "HugoNFT::nft with such id doesn't exist");
require(
bytes(description).length > 0 && bytes(description).length <= 300,
"HugoNFT::invalid NFT description length"
);
_NFTs[tokenId].description = description;
emit ChangeDescription(tokenId, description);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(HugoNFTAbstractImpl, ERC721)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @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.
*
* Current implementation focuses only on transfers. If it's a transfer, we only
* have to check `from != address(0)`, because the check in {ERC721-_transfer}
* guarantees `to != address(0)`.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
// Does nothing as ERC721._beforeTokenTransfer has no logic
super._beforeTokenTransfer(from, to, tokenId);
// transferFrom was called
if (from != address(0)) {
uint256[] storage tokenIdsOfFrom = _tokenIdsOfAccount[from];
uint256[] storage tokenIdsOfTo = _tokenIdsOfAccount[to];
NFT storage transferringNFT = _NFTs[tokenId];
uint256 lastIndexInIdsFrom = tokenIdsOfFrom.length - 1;
uint256 transferringTokenIndex = transferringNFT.index;
if (transferringTokenIndex != lastIndexInIdsFrom) {
uint256 lastIdFrom = tokenIdsOfFrom[lastIndexInIdsFrom];
NFT storage lastNFTFrom = _NFTs[lastIdFrom];
tokenIdsOfFrom[transferringTokenIndex] = lastIdFrom;
lastNFTFrom.index = transferringTokenIndex;
}
uint256 transferringTokenNewIndex = tokenIdsOfTo.length;
tokenIdsOfTo.push(tokenId);
transferringNFT.index = transferringTokenNewIndex;
tokenIdsOfFrom.pop();
}
}
/**
* @dev Computes and returns the hash of the seed
*
* First converts seed to `bytes memory` array by getting each trait id from seed,
* converting it to bytes32 and putting these bytes into in seed bytes representation.
* Then hashes the bytes representation using keccak256.
*
* *Note*: Should be called only on valid seeds!
* *Note*: The input seed has its right trailing zeroes in it truncated before hashing.
*
* For example, we have `minAttributesAmount` equal to 3. Then:
* 1. _getSeedHash([1,2,3,0,0]) == _getSeedHash([1,2,3])
* 2. _getSeedHash([1,2,3,0,1]) == _getSeedHash([1,2,3,0,1]) != _getSeedHash([1,2,3,1])
*
* Returns a bytes32 result of calling keccak256 on the input seed.
*/
function _getSeedHash(uint256[] calldata validSeed) internal view returns (bytes32) {
uint256[] memory validSeedNoTrailingZeroes = _getWithoutTrailingZeroes(validSeed);
bytes memory seedBytes = new bytes(32 * validSeedNoTrailingZeroes.length);
for (uint256 i = 0; i < validSeedNoTrailingZeroes.length; i++) {
uint256 traitId = validSeedNoTrailingZeroes[i];
seedBytes = bytes.concat(seedBytes, bytes32(traitId));
}
return keccak256(seedBytes);
}
// todo discuss error return
/**
* @dev Checks whether input seed is valid
*
* Seed is an array of trait ids of attributes, used to generate NFT.
* Input seed length shouldn't be less than `minAttributesAmount` and more than
* `currentAttributesAmount`. Also trait ids inside seed shouldn't be valid, i.e.
* 1) they should exist in attribute's trait array and 2) shouldn't be 0 for core
* attributes. Core attributes are those, which were added during deployment, so
* their ids are < `minAttributesAmount`.
*
* Returns true if seed is valid, otherwise - false.
*/
function _isValidSeed(uint256[] calldata seed) internal view returns (bool) {
if (seed.length > currentAttributesAmount || seed.length < minAttributesAmount) {
return false;
}
return _areValidTraitIds(seed);
}
function _isIdOfGeneratedNFT(uint256 tokenId) internal pure returns (bool) {
return tokenId < generatedHugoCap;
}
/**
* @dev Checks whether token exists
*
* If token doesn't exist it will have zero length seed and zero length CID.
* Otherwise token will have either seed length being not equal to 0,
* or CID length being equal to {HugoNFTStorage-IPFS_CID_BYTES_LENGTH}.
*
* We could define such check for seed: `nft.seed.length >= minAttributesAmount`, but
* if constructor changes, then we can have a risk of this check becoming invalid. For example,
* if we get rid of setting value to {HugoNFTStorage-minAttributesAmount} in constructor during,
* say, refactoring, this check will be invalid.
*
* Return true if token with `tokenId` exists, otherwise returns false.
*/
function _tokenExists(uint256 tokenId) internal view returns (bool) {
NFT storage nft = _NFTs[tokenId];
return nft.seed.length != 0 || bytes(nft.cid).length == IPFS_CID_BYTES_LENGTH;
}
function _getGeneratedHugoAmount() internal view returns (uint256) {
return totalSupply - exclusiveNFTsAmount;
}
/**
* @dev Checks whether seed trait ids are valid
*
* Length of the seed isn't checked, because it should be done
* before calling the function (in {HugoNFTMinter-_isValidSeed}).
* For more info see {HugoNFTMinter-_isValidSeed}.
*
* Returns true if trait ids are valid, otherwise - false
*/
function _areValidTraitIds(uint256[] calldata seed) private view returns (bool) {
for (uint256 i = 0; i < seed.length; i++ ) {
// That's one of reasons why traits are added sequentially.
// If IDs weren't provided sequentially, the only check we could do is
// by accessing a trait in some mapping, that stores info whether the trait
// with the provided id is present or not.
uint256 maxTraitIdInAttribute = _traitsOfAttribute[i].length;
// Trait ids start from 1 and are defined in a sequential order.
// Zero trait id is possible - it means that generating NFT won't have
// such attribute. But it's possible only for those attributes, which were
// added after deployment, i.e. whose ids >= `minAttributesAmount`
if ((i < minAttributesAmount && seed[i] == 0) || seed[i] > maxTraitIdInAttribute) {
return false;
}
}
return true;
}
// Just for convenience and readability
function _isNewSeed(bytes32 seed) private view returns (bool) {
return !_isUsedSeed[seed];
}
/**
* @dev Gets token id to mint a new auto-generative NFT
*
* For this type of NFTs ids are defined from 0 to 9999.
* All in all, 10'000 generated hugo NFTs.
*
* Returns a uint256 id number for a new auto-generative NFT
*/
function _getNewIdForGeneratedHugo() private view returns (uint256) {
return _getGeneratedHugoAmount();
}
/**
* @dev Gets token id to mint a new exclusive (not generated) NFT
*
* For this type of NFTs ids are defined from 10'000 and e.t.c.
* There is no cap for such NFTs.
*
* Returns a uint256 id number for a new exclusive NFT
*/
function _getNewIdForExclusiveHugo() private view returns (uint256) {
return generatedHugoCap + exclusiveNFTsAmount;
}
/**
* @dev Gets rid of trailing zeroes in valid seed array.
*
* Does not modify input data. It iterates through trait ids from the back,
* adjusting the `end` index, from which all the trait ids of the input seed are 0.
* When a non-zero values occurs, breaks the loop and returns `validSeed[:end]`
*
* Returns an array of seeds without trailing zeroes (from the right)
*/
function _getWithoutTrailingZeroes(uint256[] calldata validSeed)
private
view
returns
(uint256[] memory)
{
uint256 end = validSeed.length;
for (uint256 i = validSeed.length - 1; i >= minAttributesAmount; i--) {
if (validSeed[i] != 0) { break ;}
end = i;
}
return validSeed[:end];
}
}
|
Changes description of the NFT with provided tokenId. Requirements: - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role - `tokenId` should be an Id of existing NFT - `description` shouldn't be empty or larger than 300 bytes/
|
function changeNFTDescription(uint256 tokenId, string calldata description)
external
override(AbstractHugoNFT)
onlyRole(NFT_ADMIN_ROLE)
{
require(_tokenExists(tokenId), "HugoNFT::nft with such id doesn't exist");
require(
bytes(description).length > 0 && bytes(description).length <= 300,
"HugoNFT::invalid NFT description length"
);
_NFTs[tokenId].description = description;
emit ChangeDescription(tokenId, description);
}
| 7,221,271 |
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 REMOVEORDER407(bytes32 _orderId) external returns (bool);
| 2,554,087 |
/**
*Submitted for verification at Etherscan.io on 2021-04-21
*/
pragma solidity ^0.7.6;
// SPDX-License-Identifier: MIT
// Source code: https://github.com/DeCash-Official/smart-contracts
interface ERC20 {
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender)
external
view
returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool);
function transferMany(address[] calldata _tos, uint256[] calldata _values)
external
returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function mint(address _to, uint256 _value) external returns (bool);
function burn(uint256 _value) external returns (bool);
function burnFrom(address _from, uint256 _value) external returns (bool);
}
/**
* @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;
}
}
library Signature {
enum Std {typed, personal, stringHex}
enum Dest {transfer, transferFrom, transferMany, approve, approveAndCall}
bytes public constant ETH_SIGNED_MESSAGE_PREFIX =
"\x19Ethereum Signed Message:\n";
// `transferViaSignature`: keccak256(abi.encodePacked(address(this), from, to, value, fee, deadline, sigId))
bytes32 public constant DEST_TRANSFER =
keccak256(
abi.encodePacked(
"address Contract",
"address Sender",
"address Recipient",
"uint256 Amount (last 2 digits are decimals)",
"uint256 Fee Amount (last 2 digits are decimals)",
"address Fee Address",
"uint256 Expiration",
"uint256 Signature ID"
)
);
// `transferManyViaSignature`: keccak256(abi.encodePacked(address(this), from, to/value array, deadline, sigId))
bytes32 public constant DEST_TRANSFER_MANY =
keccak256(
abi.encodePacked(
"address Contract",
"address Sender",
"bytes32 Recipient/Amount Array hash",
"uint256 Fee Amount (last 2 digits are decimals)",
"address Fee Address",
"uint256 Expiration",
"uint256 Signature ID"
)
);
// `transferFromViaSignature`: keccak256(abi.encodePacked(address(this), signer, from, to, value, fee, deadline, sigId))
bytes32 public constant DEST_TRANSFER_FROM =
keccak256(
abi.encodePacked(
"address Contract",
"address Approved",
"address From",
"address Recipient",
"uint256 Amount (last 2 digits are decimals)",
"uint256 Fee Amount (last 2 digits are decimals)",
"address Fee Address",
"uint256 Expiration",
"uint256 Signature ID"
)
);
// `approveViaSignature`: keccak256(abi.encodePacked(address(this), from, spender, value, fee, deadline, sigId))
bytes32 public constant DEST_APPROVE =
keccak256(
abi.encodePacked(
"address Contract",
"address Approval",
"address Recipient",
"uint256 Amount (last 2 digits are decimals)",
"uint256 Fee Amount (last 2 digits are decimals)",
"address Fee Address",
"uint256 Expiration",
"uint256 Signature ID"
)
);
// `approveAndCallViaSignature`: keccak256(abi.encodePacked(address(this), from, spender, value, extraData, fee, deadline, sigId))
bytes32 public constant DEST_APPROVE_AND_CALL =
keccak256(
abi.encodePacked(
"address Contract",
"address Approval",
"address Recipient",
"uint256 Amount (last 2 digits are decimals)",
"bytes Data to Transfer",
"uint256 Fee Amount (last 2 digits are decimals)",
"address Fee Address",
"uint256 Expiration",
"uint256 Signature ID"
)
);
/**
* Utility costly function to encode bytes HEX representation as string.
*
* @param sig - signature as bytes32 to represent as string
*/
function hexToString(bytes32 sig) internal pure returns (bytes memory) {
bytes memory str = new bytes(64);
for (uint8 i = 0; i < 32; ++i) {
str[2 * i] = bytes1(
(uint8(sig[i]) / 16 < 10 ? 48 : 87) + uint8(sig[i]) / 16
);
str[2 * i + 1] = bytes1(
(uint8(sig[i]) % 16 < 10 ? 48 : 87) + (uint8(sig[i]) % 16)
);
}
return str;
}
/**
* Internal method that makes sure that the given signature corresponds to a given data and is made by `signer`.
* It utilizes three (four) standards of message signing in Ethereum, as at the moment of this smart contract
* development there is no single signing standard defined. For example, Metamask and Geth both support
* personal_sign standard, SignTypedData is only supported by Matamask, Trezor does not support "widely adopted"
* Ethereum personal_sign but rather personal_sign with fixed prefix and so on.
* Note that it is always possible to forge any of these signatures using the private key, the problem is that
* third-party wallets must adopt a single standard for signing messages.
*
* @param _data - original data which had to be signed by `signer`
* @param _signer - account which made a signature
* @param _sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param _sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
* @param _sigDest - for which type of action this signature was made for
*/
function requireSignature(
bytes32 _data,
address _signer,
bytes memory _sig,
Std _sigStd,
Dest _sigDest
) internal {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// solium-disable-line security/no-inline-assembly
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if (v < 27) v += 27;
if (_sigStd == Std.typed) {
bytes32 dest;
if (_sigDest == Dest.transfer) {
dest = DEST_TRANSFER;
} else if (_sigDest == Dest.transferMany) {
dest = DEST_TRANSFER_MANY;
} else if (_sigDest == Dest.transferFrom) {
dest = DEST_TRANSFER_FROM;
} else if (_sigDest == Dest.approve) {
dest = DEST_APPROVE;
} else if (_sigDest == Dest.approveAndCall) {
dest = DEST_APPROVE_AND_CALL;
}
// Typed signature. This is the most likely scenario to be used and accepted
require(
_signer ==
ecrecover(
keccak256(abi.encodePacked(dest, _data)),
v,
r,
s
),
"Invalid typed signature"
);
} else if (_sigStd == Std.personal) {
// Ethereum signed message signature (Geth and Trezor)
require(
_signer ==
ecrecover(
keccak256(
abi.encodePacked(
ETH_SIGNED_MESSAGE_PREFIX,
"32",
_data
)
),
v,
r,
s
) || // Geth-adopted
_signer ==
ecrecover(
keccak256(
abi.encodePacked(
ETH_SIGNED_MESSAGE_PREFIX,
"\x20",
_data
)
),
v,
r,
s
), // Trezor-adopted
"Invalid personal signature"
);
} else {
// == 2; Signed string hash signature (the most expensive but universal)
require(
_signer ==
ecrecover(
keccak256(
abi.encodePacked(
ETH_SIGNED_MESSAGE_PREFIX,
"64",
hexToString(_data)
)
),
v,
r,
s
) || // Geth
_signer ==
ecrecover(
keccak256(
abi.encodePacked(
ETH_SIGNED_MESSAGE_PREFIX,
"\x40",
hexToString(_data)
)
),
v,
r,
s
), // Trezor
"Invalid stringHex signature"
);
}
}
/**
* This function return the signature of the array of recipient/value pair
*
* @param _tos[] - array of account recipients
* @param _values[] - array of amount
*/
function calculateManySig(address[] memory _tos, uint256[] memory _values)
internal
pure
returns (bytes32)
{
bytes32 tv = keccak256(abi.encodePacked(_tos[0], _values[0]));
uint256 ln = _tos.length;
for (uint8 x = 1; x < ln; x++) {
tv = keccak256(abi.encodePacked(tv, _tos[x], _values[x]));
}
return tv;
}
}
interface DeCashStorageInterface {
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint256);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int256);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint256 _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int256 _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
}
/// @title Base settings / modifiers for each contract in DeCash Token (Credits David Rugendyke/Rocket Pool)
/// @author Fabrizio Amodio (ZioFabry)
abstract contract DeCashBase {
// Version of the contract
uint8 public version;
// The main storage contract where primary persistant storage is maintained
DeCashStorageInterface internal _decashStorage = DeCashStorageInterface(0);
/**
* @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract
*/
modifier onlyLatestContract(
string memory _contractName,
address _contractAddress
) {
require(
_contractAddress ==
_getAddress(
keccak256(
abi.encodePacked("contract.address", _contractName)
)
),
"Invalid or outdated contract"
);
_;
}
modifier onlyOwner() {
require(_isOwner(msg.sender), "Account is not the owner");
_;
}
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Account is not an admin");
_;
}
modifier onlySuperUser() {
require(_isSuperUser(msg.sender), "Account is not a super user");
_;
}
modifier onlyDelegator(address _address) {
require(_isDelegator(_address), "Account is not a delegator");
_;
}
modifier onlyFeeRecipient(address _address) {
require(_isFeeRecipient(_address), "Account is not a fee recipient");
_;
}
modifier onlyRole(string memory _role) {
require(_roleHas(_role, msg.sender), "Account does not match the role");
_;
}
/// @dev Set the main DeCash Storage address
constructor(address _decashStorageAddress) {
// Update the contract address
_decashStorage = DeCashStorageInterface(_decashStorageAddress);
}
function isOwner(address _address) external view returns (bool) {
return _isOwner(_address);
}
function isAdmin(address _address) external view returns (bool) {
return _isAdmin(_address);
}
function isSuperUser(address _address) external view returns (bool) {
return _isSuperUser(_address);
}
function isDelegator(address _address) external view returns (bool) {
return _isDelegator(_address);
}
function isFeeRecipient(address _address) external view returns (bool) {
return _isFeeRecipient(_address);
}
function isBlacklisted(address _address) external view returns (bool) {
return _isBlacklisted(_address);
}
/// @dev Get the address of a network contract by name
function _getContractAddress(string memory _contractName)
internal
view
returns (address)
{
// Get the current contract address
address contractAddress =
_getAddress(
keccak256(abi.encodePacked("contract.address", _contractName))
);
// Check it
require(contractAddress != address(0x0), "Contract not found");
// Return
return contractAddress;
}
/// @dev Get the name of a network contract by address
function _getContractName(address _contractAddress)
internal
view
returns (string memory)
{
// Get the contract name
string memory contractName =
_getString(
keccak256(abi.encodePacked("contract.name", _contractAddress))
);
// Check it
require(
keccak256(abi.encodePacked(contractName)) !=
keccak256(abi.encodePacked("")),
"Contract not found"
);
// Return
return contractName;
}
/// @dev Role Management
function _roleHas(string memory _role, address _address)
internal
view
returns (bool)
{
return
_getBool(
keccak256(abi.encodePacked("access.role", _role, _address))
);
}
function _isOwner(address _address) internal view returns (bool) {
return _roleHas("owner", _address);
}
function _isAdmin(address _address) internal view returns (bool) {
return _roleHas("admin", _address);
}
function _isSuperUser(address _address) internal view returns (bool) {
return _roleHas("admin", _address) || _isOwner(_address);
}
function _isDelegator(address _address) internal view returns (bool) {
return _roleHas("delegator", _address) || _isOwner(_address);
}
function _isFeeRecipient(address _address) internal view returns (bool) {
return _roleHas("fee", _address) || _isOwner(_address);
}
function _isBlacklisted(address _address) internal view returns (bool) {
return _roleHas("blacklisted", _address) && !_isOwner(_address);
}
/// @dev Storage get methods
function _getAddress(bytes32 _key) internal view returns (address) {
return _decashStorage.getAddress(_key);
}
function _getUint(bytes32 _key) internal view returns (uint256) {
return _decashStorage.getUint(_key);
}
function _getString(bytes32 _key) internal view returns (string memory) {
return _decashStorage.getString(_key);
}
function _getBytes(bytes32 _key) internal view returns (bytes memory) {
return _decashStorage.getBytes(_key);
}
function _getBool(bytes32 _key) internal view returns (bool) {
return _decashStorage.getBool(_key);
}
function _getInt(bytes32 _key) internal view returns (int256) {
return _decashStorage.getInt(_key);
}
function _getBytes32(bytes32 _key) internal view returns (bytes32) {
return _decashStorage.getBytes32(_key);
}
function _getAddressS(string memory _key) internal view returns (address) {
return _decashStorage.getAddress(keccak256(abi.encodePacked(_key)));
}
function _getUintS(string memory _key) internal view returns (uint256) {
return _decashStorage.getUint(keccak256(abi.encodePacked(_key)));
}
function _getStringS(string memory _key)
internal
view
returns (string memory)
{
return _decashStorage.getString(keccak256(abi.encodePacked(_key)));
}
function _getBytesS(string memory _key)
internal
view
returns (bytes memory)
{
return _decashStorage.getBytes(keccak256(abi.encodePacked(_key)));
}
function _getBoolS(string memory _key) internal view returns (bool) {
return _decashStorage.getBool(keccak256(abi.encodePacked(_key)));
}
function _getIntS(string memory _key) internal view returns (int256) {
return _decashStorage.getInt(keccak256(abi.encodePacked(_key)));
}
function _getBytes32S(string memory _key) internal view returns (bytes32) {
return _decashStorage.getBytes32(keccak256(abi.encodePacked(_key)));
}
/// @dev Storage set methods
function _setAddress(bytes32 _key, address _value) internal {
_decashStorage.setAddress(_key, _value);
}
function _setUint(bytes32 _key, uint256 _value) internal {
_decashStorage.setUint(_key, _value);
}
function _setString(bytes32 _key, string memory _value) internal {
_decashStorage.setString(_key, _value);
}
function _setBytes(bytes32 _key, bytes memory _value) internal {
_decashStorage.setBytes(_key, _value);
}
function _setBool(bytes32 _key, bool _value) internal {
_decashStorage.setBool(_key, _value);
}
function _setInt(bytes32 _key, int256 _value) internal {
_decashStorage.setInt(_key, _value);
}
function _setBytes32(bytes32 _key, bytes32 _value) internal {
_decashStorage.setBytes32(_key, _value);
}
function _setAddressS(string memory _key, address _value) internal {
_decashStorage.setAddress(keccak256(abi.encodePacked(_key)), _value);
}
function _setUintS(string memory _key, uint256 _value) internal {
_decashStorage.setUint(keccak256(abi.encodePacked(_key)), _value);
}
function _setStringS(string memory _key, string memory _value) internal {
_decashStorage.setString(keccak256(abi.encodePacked(_key)), _value);
}
function _setBytesS(string memory _key, bytes memory _value) internal {
_decashStorage.setBytes(keccak256(abi.encodePacked(_key)), _value);
}
function _setBoolS(string memory _key, bool _value) internal {
_decashStorage.setBool(keccak256(abi.encodePacked(_key)), _value);
}
function _setIntS(string memory _key, int256 _value) internal {
_decashStorage.setInt(keccak256(abi.encodePacked(_key)), _value);
}
function _setBytes32S(string memory _key, bytes32 _value) internal {
_decashStorage.setBytes32(keccak256(abi.encodePacked(_key)), _value);
}
/// @dev Storage delete methods
function _deleteAddress(bytes32 _key) internal {
_decashStorage.deleteAddress(_key);
}
function _deleteUint(bytes32 _key) internal {
_decashStorage.deleteUint(_key);
}
function _deleteString(bytes32 _key) internal {
_decashStorage.deleteString(_key);
}
function _deleteBytes(bytes32 _key) internal {
_decashStorage.deleteBytes(_key);
}
function _deleteBool(bytes32 _key) internal {
_decashStorage.deleteBool(_key);
}
function _deleteInt(bytes32 _key) internal {
_decashStorage.deleteInt(_key);
}
function _deleteBytes32(bytes32 _key) internal {
_decashStorage.deleteBytes32(_key);
}
function _deleteAddressS(string memory _key) internal {
_decashStorage.deleteAddress(keccak256(abi.encodePacked(_key)));
}
function _deleteUintS(string memory _key) internal {
_decashStorage.deleteUint(keccak256(abi.encodePacked(_key)));
}
function _deleteStringS(string memory _key) internal {
_decashStorage.deleteString(keccak256(abi.encodePacked(_key)));
}
function _deleteBytesS(string memory _key) internal {
_decashStorage.deleteBytes(keccak256(abi.encodePacked(_key)));
}
function _deleteBoolS(string memory _key) internal {
_decashStorage.deleteBool(keccak256(abi.encodePacked(_key)));
}
function _deleteIntS(string memory _key) internal {
_decashStorage.deleteInt(keccak256(abi.encodePacked(_key)));
}
function _deleteBytes32S(string memory _key) internal {
_decashStorage.deleteBytes32(keccak256(abi.encodePacked(_key)));
}
}
/// @title DeCash Token Multisignature Management
/// @author Fabrizio Amodio (ZioFabry)
abstract contract DeCashMultisignature {
bytes32[] public allOperations;
mapping(bytes32 => uint256) public allOperationsIndicies;
mapping(bytes32 => uint256) public votesCountByOperation;
mapping(bytes32 => address) public firstByOperation;
mapping(bytes32 => mapping(address => uint8)) public votesOwnerByOperation;
mapping(bytes32 => address[]) public votesIndicesByOperation;
uint256 public signerGeneration;
address internal _insideCallSender;
uint256 internal _insideCallCount;
event RequiredSignerChanged(
uint256 newRequiredSignature,
uint256 generation
);
event OperationCreated(bytes32 operation, address proposer);
event OperationUpvoted(bytes32 operation, address voter);
event OperationPerformed(bytes32 operation, address performer);
event OperationCancelled(bytes32 operation, address performer);
/**
* @dev Allows to perform method only after many owners call it with the same arguments
* @param _howMany defines how mant signature are required
* @param _generation multiusignature generation
*/
modifier onlyMultiSignature(uint256 _howMany, uint256 _generation) {
if (_checkMultiSignature(_howMany, _generation)) {
bool update = (_insideCallSender == address(0));
if (update) {
_insideCallSender = msg.sender;
_insideCallCount = _howMany;
}
_;
if (update) {
_insideCallSender = address(0);
_insideCallCount = 0;
}
}
}
/**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/
function cancelOperation(bytes32 operation) external {
require(votesCountByOperation[operation] > 0, "Operation not found");
_deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
/**
* @dev onlyManyOwners modifier helper
* @param _howMany defines how mant signature are required
* @param _generation multiusignature generation
*/
function _checkMultiSignature(uint256 _howMany, uint256 _generation)
internal
returns (bool)
{
if (_howMany < 2) return true;
if (_insideCallSender == msg.sender) {
require(_howMany <= _insideCallCount, "howMany > _insideCallCount");
return true;
}
bytes32 operation = keccak256(abi.encodePacked(msg.data, _generation));
uint256 operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (firstByOperation[operation] == address(0)) {
firstByOperation[operation] = msg.sender;
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, msg.sender);
} else {
require(
votesOwnerByOperation[operation][msg.sender] == 0,
"[operation][msg.sender] != 0"
);
}
votesIndicesByOperation[operation].push(msg.sender);
votesOwnerByOperation[operation][msg.sender] = 1;
emit OperationUpvoted(operation, msg.sender);
if (operationVotesCount < _howMany) return false;
_deleteOperation(operation);
emit OperationPerformed(operation, msg.sender);
return true;
}
/**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/
function _deleteOperation(bytes32 operation) internal {
uint256 index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) {
// Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
delete allOperations[allOperations.length - 1];
delete allOperationsIndicies[operation];
delete votesCountByOperation[operation];
delete firstByOperation[operation];
uint8 x;
uint256 ln = votesIndicesByOperation[operation].length;
for (x = 0; x < ln; x++) {
delete votesOwnerByOperation[operation][
votesIndicesByOperation[operation][x]
];
}
for (x = 0; x < ln; x++) {
votesIndicesByOperation[operation].pop();
}
}
}
/// @title DeCash Token implementation based on the DeCash perpetual storage
/// @author Fabrizio Amodio (ZioFabry)
contract DeCashToken is DeCashBase, DeCashMultisignature, ERC20 {
using SafeMath for uint256;
string private _name;
string private _symbol;
uint8 private _decimals;
modifier onlyLastest {
require(
address(this) ==
_getAddress(
keccak256(abi.encodePacked("contract.address", "token"))
) ||
address(this) ==
_getAddress(
keccak256(abi.encodePacked("contract.address", "proxy"))
),
"Invalid or outdated contract"
);
_;
}
modifier whenNotPaused {
require(!isPaused(), "Contract is paused");
_;
}
modifier whenPaused {
require(isPaused(), "Contract is not paused");
_;
}
event Paused(address indexed from);
event Unpaused(address indexed from);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
// Construct
constructor(address _decashStorageAddress)
DeCashBase(_decashStorageAddress)
{
version = 1;
}
function initialize(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public onlyOwner {
uint256 currentVersion =
_getUint(keccak256(abi.encodePacked("token.version", _tokenName)));
if (currentVersion == 0) {
_name = _tokenName;
_symbol = _tokenSymbol;
_decimals = _tokenDecimals;
_setString(keccak256(abi.encodePacked("token.name", _name)), _name);
_setString(
keccak256(abi.encodePacked("token.symbol", _name)),
_symbol
);
_setUint(
keccak256(abi.encodePacked("token.decimals", _name)),
_decimals
);
_setBool(
keccak256(abi.encodePacked("contract.paused", _name)),
false
);
_setUint(keccak256(abi.encodePacked("mint.reqSign", _name)), 1);
}
if (currentVersion != version) {
_setUint(
keccak256(abi.encodePacked("token.version", _name)),
version
);
}
}
function isPaused() public view returns (bool) {
return _getBool(keccak256(abi.encodePacked("contract.paused", _name)));
}
/**
* @dev Allows owners to change number of required signature for multiSignature Operations
* @param _reqsign defines how many signature is required
*/
function changeRequiredSigners(uint256 _reqsign)
external
onlySuperUser
onlyLastest
returns (uint256)
{
_setReqSign(_reqsign);
uint256 _generation = _getSignGeneration() + 1;
_setSignGeneration(_generation);
emit RequiredSignerChanged(_reqsign, _generation);
return _generation;
}
// ERC20 Implementation
function name() external view returns (string memory) {
return _name;
}
function symbol() external view returns (string memory) {
return _symbol;
}
function decimals() external view returns (uint8) {
return _decimals;
}
function totalSupply() external view returns (uint256) {
return _getTotalSupply();
}
function pause() external onlySuperUser onlyLastest whenNotPaused {
_setBool(keccak256(abi.encodePacked("contract.paused", _name)), true);
emit Paused(msg.sender);
}
function unpause() external onlySuperUser onlyLastest whenPaused {
_setBool(keccak256(abi.encodePacked("contract.paused", _name)), false);
emit Unpaused(msg.sender);
}
function balanceOf(address _owner)
external
view
override
returns (uint256)
{
return _getBalance(_owner);
}
function allowance(address _owner, address _spender)
external
view
override
returns (uint256)
{
return _getAllowed(_owner, _spender);
}
function transfer(address _to, uint256 _value)
external
override
onlyLastest
whenNotPaused
returns (bool)
{
return _transfer(msg.sender, _to, _value);
}
function transferMany(address[] calldata _tos, uint256[] calldata _values)
external
override
onlyLastest
whenNotPaused
returns (bool)
{
return _transferMany(msg.sender, _tos, _values);
}
function transferFrom(
address _from,
address _to,
uint256 _value
) external override onlyLastest whenNotPaused returns (bool) {
return _transferFrom(msg.sender, _from, _to, _value);
}
function approve(address _spender, uint256 _value)
external
override
onlyLastest
whenNotPaused
returns (bool)
{
return _approve(msg.sender, _spender, _value);
}
function burn(uint256 _value)
external
override
onlyLastest
whenNotPaused
returns (bool)
{
return _burn(msg.sender, _value);
}
function burnFrom(address _from, uint256 _value)
external
override
onlyLastest
whenNotPaused
returns (bool)
{
_approve(_from, msg.sender, _getAllowed(_from, msg.sender).sub(_value));
return _burn(_from, _value);
}
function mint(address _to, uint256 _value)
external
override
onlySuperUser
onlyLastest
whenNotPaused
onlyMultiSignature(_getReqSign(), _getSignGeneration())
returns (bool success)
{
_addBalance(_to, _value);
_addTotalSupply(_value);
emit Transfer(address(0), _to, _value);
return true;
}
/**
* This function distincts transaction signer from transaction executor. It allows anyone to transfer tokens
* from the `from` account by providing a valid signature, which can only be obtained from the `from` account owner.
* Note that passed parameter sigId is unique and cannot be passed twice (prevents replay attacks). When there's
* a need to make signature once again (because the first on is lost or whatever), user should sign the message
* with the same sigId, thus ensuring that the previous signature won't be used if the new one passes.
* Use case: the user wants to send some tokens to other user or smart contract, but don't have ether to do so.
*
* @param _from - the account giving its signature to transfer `value` tokens to `to` address
* @param _to - the account receiving `value` tokens
* @param _value - the value in tokens to transfer
* @param _fee - a fee to pay to `feeRecipient`
* @param _feeRecipient - account which will receive fee
* @param _deadline - until when the signature is valid
* @param _sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param _sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param _sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
*/
function transferViaSignature(
address _from,
address _to,
uint256 _value,
uint256 _fee,
address _feeRecipient,
uint256 _deadline,
uint256 _sigId,
bytes calldata _sig,
Signature.Std _sigStd
) external onlyLastest {
_validateViaSignatureParams(
msg.sender,
_from,
_feeRecipient,
_deadline,
_sigId
);
Signature.requireSignature(
keccak256(
abi.encodePacked(
address(this),
_from,
_to,
_value,
_fee,
_feeRecipient,
_deadline,
_sigId
)
),
_from,
_sig,
_sigStd,
Signature.Dest.transfer
);
_subBalance(_from, _value.add(_fee)); // Subtract (value + fee)
_addBalance(_to, _value);
emit Transfer(_from, _to, _value);
if (_fee > 0) {
_addBalance(_feeRecipient, _fee);
emit Transfer(_from, _feeRecipient, _fee);
}
_burnSigId(_from, _sigId);
}
/**
* This function distincts transaction signer from transaction executor. It allows anyone to transfer tokens
* from the `from` account to multiple recipient address by providing a valid signature, which can only be obtained from the `from` account owner.
* Note that passed parameter sigId is unique and cannot be passed twice (prevents replay attacks). When there's
* a need to make signature once again (because the first on is lost or whatever), user should sign the message
* with the same sigId, thus ensuring that the previous signature won't be used if the new one passes.
* Also note that the 1st recipient must be a valid fee receiver
* Use case: the user wants to send some tokens to multiple users or smart contracts, but don't have ether to do so.
*
* @param _from - the account giving its signature to transfer `value` tokens to `to` address
* @param _tos[] - array of account recipients
* @param _values[] - array of amount
* @param _fee - a fee to pay to `feeRecipient`
* @param _feeRecipient - account which will receive fee
* @param _deadline - until when the signature is valid
* @param _sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param _sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param _sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
*/
function transferManyViaSignature(
address _from,
address[] calldata _tos,
uint256[] calldata _values,
uint256 _fee,
address _feeRecipient,
uint256 _deadline,
uint256 _sigId,
bytes calldata _sig,
Signature.Std _sigStd
) external onlyLastest {
uint256 tosLen = _tos.length;
require(tosLen == _values.length, "Wrong array parameters");
require(tosLen <= 100, "Too many receiver");
_validateViaSignatureParams(
msg.sender,
_from,
_feeRecipient,
_deadline,
_sigId
);
bytes32 multisig = Signature.calculateManySig(_tos, _values);
Signature.requireSignature(
keccak256(
abi.encodePacked(
address(this),
_from,
multisig,
_fee,
_feeRecipient,
_deadline,
_sigId
)
),
_from,
_sig,
_sigStd,
Signature.Dest.transferMany
);
_subBalance(_from, _calculateTotal(_values).add(_fee));
for (uint8 x = 0; x < tosLen; x++) {
_addBalance(_tos[x], _values[x]);
emit Transfer(_from, _tos[x], _values[x]);
}
if (_fee > 0) {
_addBalance(_feeRecipient, _fee);
emit Transfer(_from, _feeRecipient, _fee);
}
_burnSigId(_from, _sigId);
}
/**
* Same as `transferViaSignature`, but for `approve`.
* Use case: the user wants to set an allowance for the smart contract or another user without having ether on their
* balance.
*
* @param _from - the account to approve withdrawal from, which signed all below parameters
* @param _spender - the account allowed to withdraw tokens from `from` address
* @param _value - the value in tokens to approve to withdraw
* @param _fee - a fee to pay to `feeRecipient`
* @param _feeRecipient - account which will receive fee
* @param _deadline - until when the signature is valid
* @param _sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param _sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param _sigStd - chosen standard for signature validation. The signer must explicitely tell which standard they use
*/
function approveViaSignature(
address _from,
address _spender,
uint256 _value,
uint256 _fee,
address _feeRecipient,
uint256 _deadline,
uint256 _sigId,
bytes calldata _sig,
Signature.Std _sigStd
) external onlyLastest {
_validateViaSignatureParams(
msg.sender,
_from,
_feeRecipient,
_deadline,
_sigId
);
Signature.requireSignature(
keccak256(
abi.encodePacked(
address(this),
_from,
_spender,
_value,
_fee,
_feeRecipient,
_deadline,
_sigId
)
),
_from,
_sig,
_sigStd,
Signature.Dest.approve
);
if (_fee > 0) {
_subBalance(_from, _fee);
_addBalance(_feeRecipient, _fee);
emit Transfer(_from, _feeRecipient, _fee);
}
_setAllowed(_from, _spender, _value);
emit Approval(_from, _spender, _value);
_burnSigId(_from, _sigId);
}
/**
* Same as `transferViaSignature`, but for `transferFrom`.
* Use case: the user wants to withdraw tokens from a smart contract or another user who allowed the user to
* do so. Important note: the fee is subtracted from the `value`, and `to` address receives `value - fee`.
*
* @param _signer - the address allowed to call transferFrom, which signed all below parameters
* @param _from - the account to make withdrawal from
* @param _to - the address of the recipient
* @param _value - the value in tokens to withdraw
* @param _fee - a fee to pay to `feeRecipient`
* @param _feeRecipient - account which will receive fee
* @param _deadline - until when the signature is valid
* @param _sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param _sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param _sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
*/
function transferFromViaSignature(
address _signer,
address _from,
address _to,
uint256 _value,
uint256 _fee,
address _feeRecipient,
uint256 _deadline,
uint256 _sigId,
bytes calldata _sig,
Signature.Std _sigStd
) external onlyLastest {
_validateViaSignatureParams(
msg.sender,
_from,
_feeRecipient,
_deadline,
_sigId
);
Signature.requireSignature(
keccak256(
abi.encodePacked(
address(this),
_from,
_to,
_value,
_fee,
_feeRecipient,
_deadline,
_sigId
)
),
_signer,
_sig,
_sigStd,
Signature.Dest.transferFrom
);
_subAllowed(_from, _signer, _value.add(_fee));
_subBalance(_from, _value.add(_fee)); // Subtract (value + fee)
_addBalance(_to, _value);
emit Transfer(_from, _to, _value);
if (_fee > 0) {
_addBalance(_feeRecipient, _fee);
emit Transfer(_from, _feeRecipient, _fee);
}
_burnSigId(_from, _sigId);
}
// Total Supply Handling
function _getTotalSupply() internal view returns (uint256) {
return
_getUint(keccak256(abi.encodePacked("token.totalSupply", _name)));
}
function _setTotalSupply(uint256 _supply) internal {
_setUint(
keccak256(abi.encodePacked("token.totalSupply", _name)),
_supply
);
}
function _addTotalSupply(uint256 _supply) internal {
_setTotalSupply(_getTotalSupply().add(_supply));
}
function _subTotalSupply(uint256 _supply) internal {
_setTotalSupply(_getTotalSupply().sub(_supply));
}
// Allowed Handling
function _getAllowed(address _owner, address _spender)
internal
view
returns (uint256)
{
return
_getUint(
keccak256(
abi.encodePacked("token.allowed", _name, _owner, _spender)
)
);
}
function _setAllowed(
address _owner,
address _spender,
uint256 _remaining
) internal {
_setUint(
keccak256(
abi.encodePacked("token.allowed", _name, _owner, _spender)
),
_remaining
);
}
function _addAllowed(
address _owner,
address _spender,
uint256 _balance
) internal {
_setAllowed(
_owner,
_spender,
_getAllowed(_owner, _spender).add(_balance)
);
}
function _subAllowed(
address _owner,
address _spender,
uint256 _balance
) internal {
_setAllowed(
_owner,
_spender,
_getAllowed(_owner, _spender).sub(_balance)
);
}
// Balance Handling
function _getBalance(address _owner) internal view returns (uint256) {
return
_getUint(
keccak256(abi.encodePacked("token.balance", _name, _owner))
);
}
function _setBalance(address _owner, uint256 _balance) internal {
require(!_isBlacklisted(_owner), "Blacklisted");
_setUint(
keccak256(abi.encodePacked("token.balance", _name, _owner)),
_balance
);
}
function _addBalance(address _owner, uint256 _balance) internal {
_setBalance(_owner, _getBalance(_owner).add(_balance));
}
function _subBalance(address _owner, uint256 _balance) internal {
_setBalance(_owner, _getBalance(_owner).sub(_balance));
}
// Other Variable Handling
function _getReqSign() internal view returns (uint256) {
return _getUint(keccak256(abi.encodePacked("mint.reqSign", _name)));
}
function _getSignGeneration() internal view returns (uint256) {
return _getUint(keccak256(abi.encodePacked("sign.generation", _name)));
}
function _getUsedSigIds(address _signer, uint256 _sigId)
internal
view
returns (bool)
{
return
_getBool(
keccak256(
abi.encodePacked("sign.generation", _name, _signer, _sigId)
)
);
}
function _setReqSign(uint256 _reqsign) internal {
_setUint(keccak256(abi.encodePacked("mint.reqSign", _name)), _reqsign);
}
function _setSignGeneration(uint256 _generation) internal {
_setUint(
keccak256(abi.encodePacked("sign.generation", _name)),
_generation
);
}
function _setUsedSigIds(
address _signer,
uint256 _sigId,
bool _used
) internal {
_setBool(
keccak256(
abi.encodePacked("sign.generation", _name, _signer, _sigId)
),
_used
);
}
function _burn(address _from, uint256 _value) internal returns (bool) {
_subBalance(_from, _value);
_subTotalSupply(_value);
emit Transfer(_from, address(0), _value);
return true;
}
function _transfer(
address _sender,
address _to,
uint256 _value
) internal returns (bool) {
_subBalance(_sender, _value);
_addBalance(_to, _value);
emit Transfer(_sender, _to, _value);
return true;
}
function _transferMany(
address _sender,
address[] calldata _tos,
uint256[] calldata _values
) internal returns (bool) {
uint256 tosLen = _tos.length;
require(tosLen == _values.length, "Wrong array parameter");
require(tosLen <= 100, "Too many receiver");
_subBalance(_sender, _calculateTotal(_values));
for (uint8 x = 0; x < tosLen; x++) {
_addBalance(_tos[x], _values[x]);
emit Transfer(_sender, _tos[x], _values[x]);
}
return true;
}
function _transferFrom(
address _sender,
address _from,
address _to,
uint256 _value
) internal returns (bool) {
_subAllowed(_from, _sender, _value);
_subBalance(_from, _value);
_addBalance(_to, _value);
emit Transfer(_from, _to, _value);
return true;
}
function _approve(
address _sender,
address _spender,
uint256 _value
) internal returns (bool) {
_setAllowed(_sender, _spender, _value);
emit Approval(_sender, _spender, _value);
return true;
}
function _calculateTotal(uint256[] memory _values)
internal
pure
returns (uint256)
{
uint256 total = 0;
uint256 ln = _values.length;
for (uint8 x = 0; x < ln; x++) {
total = total.add(_values[x]);
}
return total;
}
// Delegated functions
/**
* These functions are used to avoid the use of the modifiers that can cause the "stack too deep" error
* also for code optimization
*/
function _validateViaSignatureParams(
address _delegator,
address _from,
address _feeRecipient,
uint256 _deadline,
uint256 _sigId
) internal view {
require(!isPaused(), "Contract paused");
require(_isDelegator(_delegator), "Sender is not a delegator");
require(_isFeeRecipient(_feeRecipient), "Invalid fee recipient");
require(block.timestamp <= _deadline, "Request expired");
require(!_getUsedSigIds(_from, _sigId), "Request already used");
}
function _burnSigId(address _from, uint256 _sigId) internal {
_setUsedSigIds(_from, _sigId, true);
}
}
contract GBPDToken is DeCashToken {
constructor(address _storage) DeCashToken(_storage) {}
}
|
These functions are used to avoid the use of the modifiers that can cause the "stack too deep" error also for code optimization/
|
function _validateViaSignatureParams(
address _delegator,
address _from,
address _feeRecipient,
uint256 _deadline,
uint256 _sigId
) internal view {
require(!isPaused(), "Contract paused");
require(_isDelegator(_delegator), "Sender is not a delegator");
require(_isFeeRecipient(_feeRecipient), "Invalid fee recipient");
require(block.timestamp <= _deadline, "Request expired");
require(!_getUsedSigIds(_from, _sigId), "Request already used");
}
| 2,007,188 |
// SPDX-License-Identifier: -- 💰 --
pragma solidity ^0.7.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Generic SafeMath Library, can be removed if the
* contract will be rewritten to ^0.8.0 Solidity compiler
*/
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) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, 'SafeMath: division by zero');
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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);
}
}
/*
* @dev Context for msg.sender and msg.data can be removed
* used in Ownable to determine msg.sender through _msgSender();
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_owner = _msgSender();
emit OwnershipTransferred(
address(0),
_owner
);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(
isOwner(),
'Ownable: caller is not the owner'
);
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(
_owner,
address(0x0)
);
_owner = address(0x0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0x0),
'Ownable: new owner is the zero address'
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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.
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* 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.
*/
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
/**
* @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.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
callOptionalReturn(
token,
abi.encodeWithSelector(
token.transfer.selector,
to,
value
)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
callOptionalReturn(
token,
abi.encodeWithSelector(
token.transferFrom.selector,
from,
to,
value
)
);
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
)
internal
{
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
value
)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(
address(this),
spender
).add(value);
callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(
address(this),
spender
).sub(value);
callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function callOptionalReturn(
IERC20 token,
bytes memory data
)
private
{
require(
address(token).isContract(),
'SafeERC20: call to non-contract'
);
(bool success, bytes memory returndata) = address(token).call(data);
require(
success,
'SafeERC20: low-level call failed'
);
if (returndata.length > 0) {
require(
abi.decode(returndata, (bool)),
'SafeERC20: ERC20 operation did not succeed'
);
}
}
}
/**
* @title LPTokenWrapper
* @dev Wraps around ERC20 that is represented as Liquidity token
* contract and is being distributed for providing liquidity for the pair.
* This token is the staking token in this system / contract.
*/
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// ONBOARDING: Specify Liquidity Token Address
IERC20 public uni = IERC20(
0xB6E544c3e420154C2C663f14eDAd92737d7FbdE5
);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
/**
* @dev Returns total supply of staked token
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns balance of specific user
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev internal function for staking LP tokens
*/
function _stake(uint256 amount) internal {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] =
_balances[msg.sender].add(amount);
uni.safeTransferFrom(
msg.sender,
address(this),
amount
);
}
/**
* @dev internal function for withdrwaing LP tokens
*/
function _withdraw(uint256 amount) internal {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] =
_balances[msg.sender].sub(amount);
uni.safeTransfer(
msg.sender,
amount
);
}
}
contract FeyLPStaking is LPTokenWrapper, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// ONBOARDING: Specify Reward Token Address (FEY)
IERC20 public fey = IERC20(
0xe8E06a5613dC86D459bC8Fb989e173bB8b256072
);
// ONBOARDING: Specify duration of single cycle for the reward distribution
// reward distribution should be announced through {notifyRewardAmount} call
uint256 public constant DURATION = 52 weeks;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(
uint256 reward
);
event Staked(
address indexed user,
uint256 amount
);
event Withdrawn(
address indexed user,
uint256 amount
);
event RewardPaid(
address indexed user,
uint256 reward
);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/**
* @dev Checks when last time the reward
* was changed based on when the distribution
* is about to be finished
*/
function lastTimeRewardApplicable()
public
view
returns (uint256)
{
return Math.min(
block.timestamp,
periodFinish
);
}
/**
* @dev Determines the ratio of reward per each token
* stakd so the relative value can be calculated
*/
function rewardPerToken()
public
view
returns (uint256)
{
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
/**
* @dev Returns amount of tokens specific address or
* staker has earned so far based on his stake and time
* the stake been active so far.
*/
function earned(
address account
)
public
view
returns (uint256)
{
return balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1E18)
.add(rewards[account]);
}
/**
* @dev Ability to stake liquidity tokens
*/
function stake(
uint256 amount
)
public
updateReward(msg.sender)
{
require(
amount > 0,
'Cannot stake 0'
);
_stake(amount);
emit Staked(
msg.sender,
amount
);
}
/**
* @dev Ability to withdraw liquidity tokens
*/
function withdraw(
uint256 amount
)
public
updateReward(msg.sender)
{
require(
amount > 0,
'Cannot withdraw 0'
);
_withdraw(amount);
emit Withdrawn(
msg.sender,
amount
);
}
/**
* @dev allows to withdraw staked tokens
*
* withdraws all staked tokens by user
* also withdraws rewards as user exits
*/
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
/**
* @dev allows to withdraw staked tokens
*
* withdraws all staked tokens by user
* also withdraws rewards as user exits
*/
function getReward()
public
updateReward(msg.sender)
returns (uint256 reward)
{
reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
fey.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
/**
* @dev Starts the distribution
*
* This must be called to start the distribution cycle
* and allow stakers to start earning rewards
*/
function notifyRewardAmount(uint256 reward)
external
onlyOwner
updateReward(address(0x0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
uint256 balance = fey.balanceOf(address(this));
require(
rewardRate <= balance.div(DURATION),
'Provided reward too high'
);
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
}
}
|
Determines the ratio of reward per each token stakd so the relative value can be calculated/
|
function rewardPerToken()
public
view
returns (uint256)
{
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
| 1,263,910 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./Ownable.sol";
import "./IERC20.sol";
import "./IUniswapV3Router.sol";
import "./IWETH.sol";
import {Path} from "./Path.sol";
contract matrEXRouterV3 is Ownable, IUniswapV3Router{
using Path for bytes;
/**
* @dev Event emitted when the charity fee is taken
* @param from: The user it is taken from
* @param token: The token that was taken from the user
* @param amount: The amount of the token taken for charity
*/
event feeTaken(address from, IERC20 token, uint256 amount);
/**
* @dev Event emitted when the charity fee is taken (in ETH)
* @param from: The user it was taken from
* @param amount: The amount of ETH taken in wei
*/
event feeTakenInETH(address from, uint256 amount);
/**
* @dev Event emmited when a token is approved for trade for the first
* time on Uniswap (check takeFeeAndApprove())
* @param token: The tokens that was approved for trade
*/
event approvedForTrade(IERC20 token);
/**
* @dev
* _charityFee: The % that is taken from each swap that gets sent to charity
* _charityAddress: The address that the charity funds get sent to
* _uniswapV3Router: Uniswap router that all swaps go through
* _WETH: The address of the WETH token
*/
uint256 private _charityFee;
address private _charityAddress;
IUniswapV3Router private _uniswapV3Router;
address private _WETH;
/**
* @dev Sets the Uniswap router, the charity fee, the charity address and
* the WETH token address
*/
constructor(){
_uniswapV3Router = IUniswapV3Router(0xE592427A0AEce92De3Edee1F18E0157C05861564);
_charityFee = 20;
_charityAddress = address(0x830be1dba01bfF12C706b967AcDeCd2fDEa48990);
_WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
/**
* @dev Calculates the fee and takes it, transfers the fee to the charity
* address and the remains to this contract.
* emits feeTaken()
* Then, it checks if there is enough approved for the swap, if not it
* approves it to the uniswap contract. Emits approvedForTrade() if so.
* @param user: The payer
* @param token: The token that will be swapped and the fee will be paid
* in
* @param totalAmount: The total amount of tokens that will be swapped, will
* be used to calculate how much the fee will be
*/
function takeFeeAndApprove(address user, IERC20 token, uint256 totalAmount) internal returns (uint256){
uint256 _feeTaken = (totalAmount * _charityFee) / 10000;
token.transferFrom(user, address(this), totalAmount - _feeTaken);
token.transferFrom(user, _charityAddress, _feeTaken);
if (token.allowance(address(this), address(_uniswapV3Router)) < totalAmount){
token.approve(address(_uniswapV3Router), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
emit approvedForTrade(token);
}
emit feeTaken(user, token, _feeTaken);
return totalAmount -= _feeTaken;
}
/**
* @dev Calculates the fee and takes it, holds the fee in the contract and
* can be sent to charity when someone calls withdraw()
* This makes sure:
* 1. That the user doesn't spend extra gas for an ERC20 transfer +
* wrap
* 2. That funds can be safely transfered to a contract
* emits feeTakenInETH()
* @param totalAmount: The total amount of tokens that will be swapped, will
* be used to calculate how much the fee will be
*/
function takeFeeETH(uint256 totalAmount) internal returns (uint256 fee){
uint256 _feeTaken = (totalAmount * _charityFee) / 10000;
emit feeTakenInETH(_msgSender(), _feeTaken);
return totalAmount - _feeTaken;
}
/**
* @dev The functions below are all the same as the Uniswap contract but
* they call takeFeeAndApprove() or takeFeeETH() (See the functions above)
* and deduct the fee from the amount that will be traded.
*/
function exactInputSingle(ExactInputSingleParams calldata params) external virtual override payable returns (uint256){
if (params.tokenIn == _WETH && msg.value >= params.amountIn){
uint256 newValue = takeFeeETH(params.amountIn);
ExactInputSingleParams memory params_ = params;
params_.amountIn = newValue;
return _uniswapV3Router.exactInputSingle{value: params_.amountIn}(params_);
}else{
IERC20 token = IERC20(params.tokenIn);
uint256 newAmount = takeFeeAndApprove(_msgSender(), token, params.amountIn);
ExactInputSingleParams memory _params = params;
_params.amountIn = newAmount;
return _uniswapV3Router.exactInputSingle(_params);
}
}
function exactInput(ExactInputParams calldata params) external virtual override payable returns (uint256){
(address tokenIn, address tokenOut, uint24 fee) = params.path.decodeFirstPool();
if (tokenIn == _WETH && msg.value >= params.amountIn){
uint256 newValue = takeFeeETH(params.amountIn);
ExactInputParams memory params_ = params;
params_.amountIn = newValue;
return _uniswapV3Router.exactInput{value: params_.amountIn}(params_);
}else{
IERC20 token = IERC20(tokenIn);
uint256 newAmount = takeFeeAndApprove(_msgSender(), IERC20(token), params.amountIn);
ExactInputParams memory _params = params;
_params.amountIn = newAmount;
return _uniswapV3Router.exactInput(_params);
}
}
function exactOutputSingle(ExactOutputSingleParams calldata params) external virtual payable override returns (uint256){
if (params.tokenIn == address(_WETH) && msg.value >= params.amountOut){
uint256 newValue = takeFeeETH(params.amountOut);
ExactOutputSingleParams memory params_ = params;
params_.amountOut = newValue;
return _uniswapV3Router.exactOutputSingle{value: params_.amountOut}(params_);
}else{
IERC20 token = IERC20(params.tokenIn);
uint256 newAmount = takeFeeAndApprove(_msgSender(), token, params.amountOut);
ExactOutputSingleParams memory _params = params;
_params.amountOut = newAmount;
return _uniswapV3Router.exactOutputSingle(_params);
}
}
function exactOutput(ExactOutputParams calldata params) external virtual override payable returns (uint256){
(address tokenIn, address tokenOut, uint24 fee) = params.path.decodeFirstPool();
if (tokenIn == address(_WETH) && msg.value >= params.amountOut){
uint256 newValue = takeFeeETH(params.amountOut);
ExactOutputParams memory params_ = params;
params_.amountOut == newValue;
return _uniswapV3Router.exactOutput{value: params_.amountOut}(params_);
}else{
IERC20 token = IERC20(tokenIn);
uint256 newAmount = takeFeeAndApprove(_msgSender(), IERC20(token), params.amountOut);
ExactOutputParams memory _params = params;
_params.amountOut == newAmount;
return _uniswapV3Router.exactOutput(_params);
}
}
/**
* @dev Wraps all tokens in the contract and sends them to the charity
* address
* To know why, see takeFeeETH()
*/
function withdraw() external {
uint256 contractBalance = address(this).balance;
IWETH(_WETH).deposit{value: contractBalance}();
IWETH(_WETH).transfer(_charityAddress, contractBalance);
}
/**
* @dev Functions that only the owner can call that change the variables
* in this contract
*/
function setCharityFee(uint256 newCharityFee) external onlyOwner {
_charityFee = newCharityFee;
}
function setCharityAddress(address newCharityAddress) external onlyOwner {
_charityAddress = newCharityAddress;
}
function setUniswapV3Router(IUniswapV3Router newUniswapV3Router) external onlyOwner {
_uniswapV3Router = newUniswapV3Router;
}
function setWETH(address newWETH) external onlyOwner {
_WETH = newWETH;
}
/**
* @return Returns the % fee taken from each swap that goes to charity
*/
function charityFee() external view returns (uint256) {
return _charityFee;
}
/**
* @return The address that the "Charity Fee" is sent to
*/
function charityAddress() external view returns (address) {
return _charityAddress;
}
/**
* @return The router that all swaps will be directed through
*/
function uniswapV3Router() external view returns (IUniswapV3Router) {
return _uniswapV3Router;
}
/**
* @return The current WETH contract that's being used
*/
function WETH() external view returns (address) {
return _WETH;
}
}
|
Functions that only the owner can call that change the variables in this contract/
|
function setCharityFee(uint256 newCharityFee) external onlyOwner {
_charityFee = newCharityFee;
}
| 5,778,444 |
pragma solidity ^0.4.15;
contract testAddress {
function f() {
address x = 0x123;
address myAddress = this;
if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10);
}
function g() {
address nameReg = 0x72ba7d8e73fe8eb666ea66babc8116a41bfb10e2;
nameReg.call("register", "MyName");
nameReg.call(bytes4(keccak256("fun(uint256)")), 1);
}
}
contract test {
enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
ActionChoices choice;
ActionChoices constant defaultChoice = ActionChoices.GoStraight;
function setGoStraight() {
choice = ActionChoices.GoStraight;
}
// Since enum types are not part of the ABI, the signature of "getChoice"
// will automatically be changed to "getChoice() returns (uint8)"
// for all matters external to Solidity. The integer type used is just
// large enough to hold all enum values, i.e. if you have more values,
// `uint16` will be used and so on.
function getChoice() returns (ActionChoices) {
return choice;
}
function getDefaultChoice() returns (uint) {
return uint(defaultChoice);
}
}
library ArrayUtils {
// internal functions can be used in internal library functions because
// they will be part of the same code context
function map(uint[] memory self, function (uint) returns (uint) f)
internal
returns (uint[] memory r)
{
r = new uint[](self.length);
for (uint i = 0; i < self.length; i++) {
r[i] = f(self[i]);
}
}
function reduce(
uint[] memory self,
function (uint, uint) returns (uint) f
)
internal
returns (uint r)
{
r = self[0];
for (uint i = 1; i < self.length; i++) {
r = f(r, self[i]);
}
}
function range(uint length) internal returns (uint[] memory r) {
r = new uint[](length);
for (uint i = 0; i < r.length; i++) {
r[i] = i;
}
}
}
contract Pyramid {
using ArrayUtils for *;
function pyramid(uint l) returns (uint) {
ArrayUtils.range(l);
}
function square(uint x) internal returns (uint) {
return x * x;
}
function sum(uint x, uint y) internal returns (uint) {
return x + y;
}
}
contract Oracle {
struct Request {
bytes data;
function(bytes memory) external callback;
}
Request[] requests;
event NewRequest(uint);
function query(bytes data, function(bytes memory) external callback) {
requests.push(Request(data, callback));
NewRequest(requests.length - 1);
}
function reply(uint requestID, bytes response) {
// Here goes the check that the reply comes from a trusted source
requests[requestID].callback(response);
}
}
contract OracleUser {
Oracle constant oracle = Oracle(0x1234567); // known contract
function buySomething() {
oracle.query("USD", this.oracleResponse);
}
function oracleResponse(bytes response) {
require(msg.sender == address(oracle));
// Use the data
}
}
contract C {
uint[] x; // the data location of x is storage
// the data location of memoryArray is memory
function f(uint[] memoryArray) {
x = memoryArray; // works, copies the whole array to storage
var y = x; // works, assigns a pointer, data location of y is storage
y[7]; // fine, returns the 8th element
y.length = 2; // fine, modifies x through y
delete x; // fine, clears the array, also modifies y
// The following does not work; it would need to create a new temporary /
// unnamed array in storage, but storage is "statically" allocated:
// y = memoryArray;
// This does not work either, since it would "reset" the pointer, but there
// is no sensible location it could point to.
// delete y;
g(x); // calls g, handing over a reference to x
h(x); // calls h and creates an independent, temporary copy in memory
}
function g(uint[] storage storageArray) internal {}
function h(uint[] memoryArray) {}
}
contract C2 {
function f(uint len) {
uint[] memory a = new uint[](7);
bytes memory b = new bytes(len);
// Here we have a.length == 7 and b.length == len
a[6] = 8;
}
}
contract C3 {
function f() {
g([uint(1), 2, 3]);
}
function g(uint[3] _data) {
// ...
}
}
contract ArrayContract {
uint[2**20] m_aLotOfIntegers;
// Note that the following is not a pair of dynamic arrays but a
// dynamic array of pairs (i.e. of fixed size arrays of length two).
bool[2][] m_pairsOfFlags;
// newPairs is stored in memory - the default for function arguments
function setAllFlagPairs(bool[2][] newPairs) {
// assignment to a storage array replaces the complete array
m_pairsOfFlags = newPairs;
}
function setFlagPair(uint index, bool flagA, bool flagB) {
// access to a non-existing index will throw an exception
m_pairsOfFlags[index][0] = flagA;
m_pairsOfFlags[index][1] = flagB;
}
function changeFlagArraySize(uint newSize) {
// if the new size is smaller, removed array elements will be cleared
m_pairsOfFlags.length = newSize;
}
function clear() {
// these clear the arrays completely
delete m_pairsOfFlags;
delete m_aLotOfIntegers;
// identical effect here
m_pairsOfFlags.length = 0;
}
bytes m_byteData;
function byteArrays(bytes data) {
// byte arrays ("bytes") are different as they are stored without padding,
// but can be treated identical to "uint8[]"
m_byteData = data;
m_byteData.length += 7;
m_byteData[3] = 8;
delete m_byteData[2];
}
function addFlag(bool[2] flag) returns (uint) {
return m_pairsOfFlags.push(flag);
}
function createMemoryArray(uint size) returns (bytes) {
// Dynamic memory arrays are created using `new`:
uint[2][] memory arrayOfPairs = new uint[2][](size);
// Create a dynamic byte array:
bytes memory b = new bytes(200);
for (uint i = 0; i < b.length; i++)
b[i] = byte(i);
return b;
}
}
contract CrowdFunding {
// Defines a new type with two fields.
struct Funder {
address addr;
uint amount;
}
struct Campaign {
address beneficiary;
uint fundingGoal;
uint numFunders;
uint amount;
mapping (uint => Funder) funders;
}
uint numCampaigns;
mapping (uint => Campaign) campaigns;
function newCampaign(address beneficiary, uint goal) returns (uint campaignID) {
campaignID = numCampaigns++; // campaignID is return variable
// Creates new struct and saves in storage. We leave out the mapping type.
campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0);
}
function contribute(uint campaignID) payable {
Campaign storage c = campaigns[campaignID];
// Creates a new temporary memory struct, initialised with the given values
// and copies it over to storage.
// Note that you can also use Funder(msg.sender, msg.value) to initialise.
c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value});
c.amount += msg.value;
}
function checkGoalReached(uint campaignID) returns (bool reached) {
Campaign storage c = campaigns[campaignID];
if (c.amount < c.fundingGoal)
return false;
uint amount = c.amount;
c.amount = 0;
c.beneficiary.transfer(amount);
return true;
}
}
contract MappingExample {
mapping(address => uint) public balances;
function update(uint newBalance) {
balances[msg.sender] = newBalance;
}
}
contract MappingUser {
function f() returns (uint) {
MappingExample m = new MappingExample();
m.update(100);
return m.balances(this);
}
}
contract DeleteExample {
uint data;
uint[] dataArray;
function f() {
uint x = data;
delete x; // sets x to 0, does not affect data
delete data; // sets data to 0, does not affect x which still holds a copy
uint[] y = dataArray;
delete dataArray; // this sets dataArray.length to zero, but as uint[] is a complex object, also
// y is affected which is an alias to the storage object
// On the other hand: "delete y" is not valid, as assignments to local variables
// referencing storage objects can only be made from existing storage objects.
}
}
|
Creates a new temporary memory struct, initialised with the given values and copies it over to storage. Note that you can also use Funder(msg.sender, msg.value) to initialise.
|
function contribute(uint campaignID) payable {
Campaign storage c = campaigns[campaignID];
c.amount += msg.value;
}
| 6,347,288 |
./full_match/80001/0xfFdcEB6174805FD7EF82938e7fEE6bf06E22d4F5/sources/contracts/1_Storage.sol
|
Return value return value of 'number'/
|
function readNumber() public view returns (uint256){
return number;
}
| 9,534,814 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
/// @title MyNFTProject
contract MyNFTProject is ERC721, ERC721Enumerable, Pausable, Ownable, ERC721Burnable {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIdCounter;
// Base URI
string baseURI;
// Base extension
string public baseExtension = ".json";
// Cost of minting in wei
uint256 public cost = 80000000000000 wei; // 0.00008 eth = 80000000000000 wei
// Maximum mint amount per account
uint256 public maxMintAmount = 3;
// Maximum supply of tokens
uint256 public maxSupply = 10;
// Enum setting used for function status
enum STATUS {ON, OFF}
STATUS public funSetting = STATUS.OFF;
constructor(string memory _initBaseURI) ERC721("MyNFTProject", "MYNFT") {
// sets BaseURI
setBaseURI(_initBaseURI);
// starts NFT counter at 1
_tokenIdCounter.increment();
}
/// @dev sets the base URI for the NFTs
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/**
* @dev While the initial base URI is set at compilation, this function
* assigns a new base URI - available to owner
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
/// @dev Security feature that pauses the contract - available to owner
function pause() public onlyOwner {
_pause();
}
/// @dev Security feature that unpauses the contract - available to owner
function unpause() public onlyOwner {
_unpause();
}
/**
* @dev Minting function - available to the public.
* @notice Creates your entertaining collectible.
* Requirements:
*
* - the mint amount does not exceed the allowable NFT limit per account
* - the contract is unpaused
* - the mint amount is not equal to zero
* - the mint amount does not exceed the max mint amount per account
* - the mint amount does not exceed the max supply of tokens
* - the minter has enough coin to mint
*/
function mint(uint256 _mintAmount) public payable {
require(balanceOf(msg.sender) <= 2, "Only 3 mints allowed per account");
require(!paused(), "Contract is paused");
require(_mintAmount > 0, "Mint amount is zero");
require(_mintAmount <= maxMintAmount, "Mint amount exceeds the maximum mint amount");
uint256 supply = totalSupply();
require(supply + _mintAmount <= maxSupply, "Mint amount exceeds the maximum supply");
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount, "Value must be equal or greater than the cost");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
/// @dev Function returning an array of a collector's token IDs
/// @param _owner The collector's address
/// @return array Token IDs
function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
/**
* @dev Function returning string of a token's URI
* @param tokenId ID of token
* @return string Token's URI
* Requirements:
*
* - the tokenId must exist
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: Token does not exist"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
/**
* @dev Function updating minting cost - available to owner
* @param _newCost The cost of minting in wei
* Requirements:
*
* - the cost is greater than zero
*/
function setCost(uint256 _newCost) public onlyOwner {
require(_newCost > 0, "New cost entered is zero");
cost = _newCost;
}
/**
* @dev Function updating maximum minting amount per account - available to owner
* @param _newmaxMintAmount The maximum mint amount per account
* Requirements:
*
* - the newmaxMintAmount is greater than zero
*/
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
require(_newmaxMintAmount > 0, "Max mint amount entered is zero");
maxMintAmount = _newmaxMintAmount;
}
/**
* @dev Function updating maximum token supply - available to owner
* @param _newmaxSupply The maximum supply of tokens
* @notice This setting exists to accommodate potential future limited-run collections
* Requirements:
*
* - the newmaxSupply is greater than zero
* - the newmaxSupply is greater than the current totalSupply
*/
function setmaxSupply(uint256 _newmaxSupply) public onlyOwner {
require(_newmaxSupply > 0, "Supply entered is zero");
uint256 supply = totalSupply();
require(_newmaxSupply > supply, "Supply entered is less than total supply");
maxSupply = _newmaxSupply;
}
/// @dev Function updating base URI extension - available to owner
/// @param _newBaseExtension The base extension
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
/// @dev Function setting - available to owner
function turnOn() public onlyOwner {
funSetting = STATUS.ON;
}
/// @dev Function setting - available to owner
function turnOff() public onlyOwner {
funSetting = STATUS.OFF;
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
* @param tokenId The token ID
* @notice We wanted to include burn capability for a potential future application
* but did not want to activate functionality before all tokens were minted.
* Requirements:
*
* - function must be turned "on"
* - The caller must own `tokenId` or be an approved operator
*/
function burn(uint256 tokenId) public override {
require(funSetting == STATUS.ON, "Burn not available");
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
/**
* @dev Minting function - available to owner.
* @param to The address receiving the token
* @param tokenId The token ID
* @notice This is a failsafe function preserving the contract's ability to mint
* after burn function has been activated.
* Requirements:
*
* - function must be turned "on"
* - the contract is unpaused
* - the tokenId does not exist
* - the to address is not zero
* - the tokenId is not equal to zero
* - the mint amount does not exceed the allowable NFT limit per account
* - the mint amount does not exceed the max supply of tokens
*/
function safeMint(address to, uint256 tokenId) public onlyOwner {
require(funSetting == STATUS.ON, "Safemint not available");
require(!paused(), "Contract is paused");
require(!_exists(tokenId), "ERC721: token already minted");
require(to != address(0), "ERC721: minted to the zero address");
require(tokenId > 0, "Token ID is zero");
require(balanceOf(msg.sender) <= 2, "Only 3 mints allowed per account");
uint256 mintNumber = 1;
uint256 supply = totalSupply();
require(supply + mintNumber <= maxSupply, "Mint amount exceeds the maximum supply");
_safeMint(to, tokenId, "");
}
/**
* @dev Function checking the balance of the contract - available to owner
*/
function getContractBalance() public onlyOwner view returns (uint){
return address(this).balance;
}
/**
* @dev Function withdrawing the balance of the contract - available to owner
*/
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
/// @dev The following function overrides are required by Solidity.
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused
override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/// @dev The following function overrides are required by Solidity.
function supportsInterface(bytes4 interfaceId) public view
override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
|
Function checking the balance of the contract - available to owner/
|
function getContractBalance() public onlyOwner view returns (uint){
return address(this).balance;
}
| 1,777,215 |
pragma solidity ^0.4.20;
contract HouseHolding {
address owner = msg.sender; // админ
uint top = 0; // счетчик ид для добавления домов
struct HouseInfo {
address owner; // владелец
bool inPledge; // в залоге или нет
uint area; // площадь
bool isResidetial; // жилой или нет
uint date; // начало последнего использования
}
mapping(uint => HouseInfo) all_houses; // global id => основная информация о доме
mapping(address => uint[]) my_houses; // владелец => список global id его домов
// создание объекта недвижимости(админ)
function addHouse(address _owner, uint _area, bool _isResidential, uint _data) public {
require(
msg.sender == owner,
"only admin can add"
);
HouseInfo memory t = HouseInfo(_owner, false, _area, _isResidential, _data);
all_houses[top] = t;
my_houses[_owner].push(top);
++top;
}
//Просмотр данных об объекте недвижимости по его global id(все)
function get_house_info(uint id) public constant returns
(address, bool, uint, bool, uint) {
HouseInfo memory t = all_houses[id];
return (t.owner, t.inPledge, t.area, t.isResidetial, t.date);
}
//доп. информация о продающимся доме
struct SaleInfo {
uint id; // global id
uint price; // цена
uint time; // срок действия предложения
}
mapping(address => uint[]) my_houses_in_sale; // address => список global id моих продающихся домов
SaleInfo[] all_houses_in_sale; // список всех продающихся домов
// информация о предложении между 2мя пользователями
struct OfferInfo {
address b; // вторая сторона
uint id; // global id
}
mapping(address => OfferInfo[]) offer_for_sale_for_me; // address => список предложений, чтобы купить у address
mapping(address => OfferInfo[]) offer_for_sale_from_me; // address => список предложений address, чтобы купить у другого
// создать предложение о продаже(собственник)
function create_offer_for_sale
(uint my_house_id, uint price, uint time) public {
require(
msg.sender == all_houses[my_houses[msg.sender][my_house_id] ].owner,
"You don't own that house"
);
for(uint i = 0; i < my_houses_in_sale[msg.sender].length; ++i) { // проверка что такой дом уже не продается
if(my_houses[msg.sender][my_house_id] == my_houses_in_sale[msg.sender][i]) {
return;
}
}
SaleInfo memory t = SaleInfo(my_houses[msg.sender][my_house_id], price, time);
all_houses_in_sale.push(t);
my_houses_in_sale[msg.sender].push(my_houses[msg.sender][my_house_id]); // push global id
/* to do list
* не должен быть в предложении на подарок(убрать предложение)
* (мб)такой ид моего дома должен существовать */
}
// // удалить предложение о продаже
// function delete_offer_for_sale(uint my_house_in_sale_id) public {
// require(
// all_houses[my_houses_in_sale[msg.sender][my_house_in_sale_id] ].owner == msg.sender,
// "You don't own that house"
// );
// uint gID = my_houses_in_sale[msg.sender][my_house_in_sale_id]; // получение глобального ид дома
// for(uint q = 0; q < offer_for_sale_for_me[msg.sender].length; ++q) { /* удалить предложения о покупке */
// if(gID == offer_for_sale_for_me[msg.sender][q].id) {
// address r = offer_for_sale_for_me[msg.sender][q].b;
// for(uint w = 0; w < offer_for_sale_from_me[r].length; ++w) {
// if(gID == offer_for_sale_from_me[r][w].id) {
// delete offer_for_sale_from_me[r];
// uint[] memory arr = new uint[](offer_for_sale_from_me[r].length - 1);
// offer_for_sale_from_me[r] = arr;
// }
// }
// delete offer_for_sale_for_me[msg.sender][q];
// if(offer_for_sale_for_me[msg.sender].length != 0 && q != offer_for_sale_for_me[r].length - 1) {
// offer_for_sale_for_me[msg.sender][q] = offer_for_sale_for_me[msg.sender][offer_for_sale_for_me[msg.sender].length - 1];
// delete offer_for_sale_for_me[msg.sender][offer_for_sale_for_me[msg.sender].length - 1];
// --q;
// }
// }
// }
// /* to do list
// * возврат денег с контракта, желающим купить
// * (мб)такой ид моего продающегося дома должен существовать */
// delete my_houses_in_sale[msg.sender][my_house_in_sale_id];
// if(my_houses_in_sale[msg.sender].length != 0 && my_house_in_sale_id != my_houses_in_sale[msg.sender].length - 1) {
// my_houses_in_sale[msg.sender][my_house_in_sale_id] = my_houses_in_sale[msg.sender][my_houses_in_sale[msg.sender].length - 1];
// delete my_houses_in_sale[msg.sender][my_houses_in_sale[msg.sender].length - 1];
// }
// for(uint i = 0; i < all_houses_in_sale.length; ++i) {
// if(gID == all_houses_in_sale[i].id) {
// delete all_houses_in_sale[i];
// if(all_houses_in_sale.length != 0 && i != all_houses_in_sale.length - 1) {
// all_houses_in_sale[i] = all_houses_in_sale[all_houses_in_sale.length - 1];
// delete all_houses_in_sale[all_houses_in_sale.length - 1];
// }
// break;
// }
// }
// }
// сделать запрос на покупку
function make_offer_to_buy(uint id) public payable{ // ид из всех продающихся домов
require(
msg.value == all_houses_in_sale[id].price,
"Not enought money"
);
uint gID = all_houses_in_sale[id].id;
offer_for_sale_from_me[msg.sender].push(OfferInfo(all_houses[gID].owner, gID)); // add в список предложений от меня (стоимость можно будет взять из списка домов, которые продает овнер и найти тот самый)
offer_for_sale_for_me[all_houses[gID].owner].push(OfferInfo(msg.sender, gID)); // add в список предложений для владельца
/* to do list
* (мб)срок действия обьявления не истек */
}
// --->> Список моих "покупок", ожидающих подтверждения
// количество "покупок", ожидающих подтверждения
function get_count_of_offer_to_buy_from_me() public constant returns (uint) {
return offer_for_sale_from_me[msg.sender].length;
}
// информация об "покупке" ожидающей подтверждения по ее ид в списке моих покупок, ожидающих подтверждения
function get_offer_to_buy_from_me_info(uint id) public constant returns (address, bool, uint, bool, uint) {
HouseInfo memory t = all_houses[offer_for_sale_from_me[msg.sender][id].id];
return (t.owner, t.inPledge, t.area, t.isResidetial, t.date);
}
// <<--- Список моих "покупок", ожидающих подтверждения
// принять запрос на покупку
// function accept_offer_to_sell(uint id) public { // ид из offer_for_sale_for_me
// /* только овнер может принимать предложения о продаже своих домов */
// /* овнеру переводятся требуемые деньги со смарт контракта */
// address buyer = offer_for_sale_for_me[msg.sender][id].b;
// uint gID = offer_for_sale_for_me[msg.sender][id].id;
// delete offer_for_sale_for_me[msg.sender][id];
// for(uint s = 0; s < offer_for_sale_for_me[msg.sender][id]) {
// }
// for(uint i = 0; i < my_houses_in_sale[msg.sender].length; ++i) {
// if(gID == my_houses_in_sale[msg.sender][i]) {
// delete_offer_for_sale(i);
// break;
// }
// }
// for(uint j = 0; j < my_houses[msg.sender].length; ++j) {
// if(gID == my_houses[msg.sender][j]) {
// delete my_houses[msg.sender][j];
// if(my_houses[msg.sender].length != 0) {
// my_houses[msg.sender][j] = my_houses[msg.sender][my_houses[msg.sender].length - 1];
// delete my_houses[msg.sender][my_houses[msg.sender].length - 1];
// }
// break;
// }
// }
// all_houses[gID].owner = offer_for_sale_for_me[msg.sender][id].b;
// all_houses[gID].date = now;
// my_houses[offer_for_sale_for_me[msg.sender][id].b].push(gID);
// }
// --->> Просмотр всех предложений о продаже
// количество всех предложени о продаже
function get_count_of_saling_houses() public constant returns(uint) {
return all_houses_in_sale.length;
}
// информация о продающемся доме по его ид в списке всех продающихся домов
function get_saling_house_info(uint id) public constant returns(address, uint, bool, bool, uint, uint, uint) { // ид в списке всех продающихся домов
HouseInfo memory t = all_houses[all_houses_in_sale[id].id];
return (t.owner, t.area, t.inPledge, t.isResidetial, t.date, all_houses_in_sale[id].price, all_houses_in_sale[id].time);
}
// <<--- Просмотр всех предложений о продаже
// --->> Все мои объекты недвижимости
// количество моих домов
function get_count_of_my_houses() public constant returns (uint) {
return my_houses[msg.sender].length;
}
// информация о моем доме по его ид в списке моих домов
function get_my_house_info(uint id) public constant returns (address, bool, uint, bool, uint) {
HouseInfo memory t = all_houses[my_houses[msg.sender][id]];
return (t.owner, t.inPledge, t.area, t.isResidetial, t.date);
}
// <<--- Все мои объекты недвижимости
// --->> Всех мои предложения о продаже
// количество моих продающихся домов
function get_count_of_my_saling_houses() public constant returns(uint) {
return my_houses_in_sale[msg.sender].length;
}
// информация о моем продающемся доме по его ид из списка моих продающихся домов
function get_my_saling_house_info(uint id) public constant returns (address, bool, uint, bool, uint) {
HouseInfo memory t = all_houses[my_houses_in_sale[msg.sender][id]];
return (t.owner, t.inPledge, t.area, t.isResidetial, t.date);
}
// << --- Всех мои предложения о продаже
mapping(address => uint[]) my_houses_in_offer_to_pledge; // address => предложения о залоге от address
SaleInfo[] all_houses_in_offer_to_pledge; // Все предложения о залоге
// Создание предложения о залоге(собственник)
function create_offer_for_pledge(uint id, uint price, uint time) public {
uint gID = my_houses[msg.sender][id];
SaleInfo memory o = SaleInfo(gID, price, time);
all_houses_in_offer_to_pledge.push(o);
my_houses_in_offer_to_pledge[msg.sender].push(gID);
}
// --->> Всех мои предложения о залоге
// Количество моих предложений о залоге
function get_count_of_my_house_to_pledge() public constant returns (uint) {
return my_houses_in_offer_to_pledge[msg.sender].length;
}
// Информация о доме, который я предлагаю взять в залог по его ид из списка моих предложений о залоге
function get_my_house_to_pledge_info(uint id) public constant returns (address, uint, bool, uint) {
HouseInfo memory h = all_houses[my_houses_in_offer_to_pledge[msg.sender][id]];
return (h.owner, h.area, h.isResidetial, h.date);
}
// <<--- Всех мои предложения о залоге
// --->> Просмотр предложений о залоге(все)
// количество всех предложений о залоге
function get_count_of_houses_to_pledge() public constant returns (uint) {
return all_houses_in_offer_to_pledge.length;
}
// информация о предложении о залоге по его ид в списке всех предложений о залоге
function get_house_to_pledge_info(uint id) public constant returns (address, uint, bool, uint) {
HouseInfo memory h = all_houses[all_houses_in_offer_to_pledge[id].id];
return (h.owner, h.area, h.isResidetial, h.date);
}
// <<--- Просмотр предложений о залоге(все)
}
|
--->> Просмотр всех предложений о продаже количество всех предложени о продаже
|
function get_count_of_saling_houses() public constant returns(uint) {
return all_houses_in_sale.length;
}
| 15,791,026 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
import "./ERC1155Inventory.sol";
import "./IERC1155InventoryBurnable.sol";
/**
* @title ERC1155InventoryBurnable, a burnable ERC1155Inventory
*/
abstract contract ERC1155InventoryBurnable is IERC1155InventoryBurnable, ERC1155Inventory {
//================================== ERC1155InventoryBurnable =======================================/
/**
* Burns some token.
* @dev See {IERC1155InventoryBurnable-burnFrom(address,uint256,uint256)}.
*/
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
} else if (id.isNonFungibleToken()) {
_burnNFT(from, id, value, false);
} else {
revert("Inventory: not a token id");
}
emit TransferSingle(sender, from, address(0), id, value);
}
/**
* Burns a batch of tokens.
* @dev See {IERC1155InventoryBurnable-batchBurnFrom(address,uint256[],uint256[])}.
*/
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
} else if (id.isNonFungibleToken()) {
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
} else {
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
//================================== Internal Helper Functions =======================================/
function _burnFungible(
address from,
uint256 id,
uint256 value
) internal {
require(value != 0, "Inventory: zero value");
uint256 balance = _balances[id][from];
require(balance >= value, "Inventory: not enough balance");
_balances[id][from] = balance - value;
// Cannot underflow
_supplies[id] -= value;
}
function _burnNFT(
address from,
uint256 id,
uint256 value,
bool isBatch
) internal {
require(value == 1, "Inventory: wrong NFT value");
require(from == address(_owners[id]), "Inventory: non-owned NFT");
_owners[id] = _BURNT_NFT_OWNER;
if (!isBatch) {
uint256 collectionId = id.getNonFungibleCollection();
// cannot underflow as balance is confirmed through ownership
--_balances[collectionId][from];
// Cannot underflow
--_supplies[collectionId];
}
}
}
|
Burns a batch of tokens. See {IERC1155InventoryBurnable-batchBurnFrom(address,uint256[],uint256[])}./
|
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
++nfCollectionCount;
}
}
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
| 985,951 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/// @title An Ownable Contract
/// @author Mariona (seaona)
/// @notice Do not use this contract on production
contract Ownable {
address private _owner;
/// @dev Get current contract owner
/// @return Address of current contract owner
function getOwner() public view returns(address) {
return _owner;
}
/// @dev Constructor that sets the _owner var to the creater of the contract
constructor() {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/// @dev 'onlyOwner' modifier that throws if called by any account other than the owner.
modifier onlyOwner {
require(msg.sender == _owner, "You are not authorized to perform this action");
_;
}
/// @dev Transfers ownership to a new address, only owner can call this function
/// @param newOwner The address of the new owner
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/// @dev Function for getting the contract owner
/// @return Address with the current contract owner
function getContractOwner() public view returns (address) {
return _owner;
}
/// @dev Event that is throwed when contract ownership is transferred
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
}
/// @title A Pausable Contract
/// @author Mariona (seaona)
/// @notice Do not use this contract on production
contract Pausable is Ownable {
bool private _paused;
/// @dev Pause contract when it's running
function pauseContract() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/// @dev Resume contract when it' not paused
function resumeContract() public onlyOwner paused {
_paused = false;
emit ResumeContract(msg.sender);
}
/// @dev Constructor that sets the _paused variable to false
constructor() {
_paused = false;
}
/// @dev 'whenNotPaused' modifier that throws if contract is Paused.
modifier whenNotPaused () {
require(_paused == false, "Contract Paused!");
_;
}
/// @dev 'Paused' modifier that throws if contract is Not Paused.
modifier paused() {
require(_paused == true, "Contract not Paused!");
_;
}
/// @dev Function that returns if Contract is Paused
/// @return Boolean saying if contract is Paused or not
function isContractPaused() public view returns (bool) {
return _paused;
}
/// @dev Paused event that emits the address that triggered the event
/// @param account The address that triggered the event
event Paused(address indexed account);
/// @dev ResumeContract event that emits the address that triggered the event
/// @param account The address that triggered the event
event ResumeContract(address indexed account);
}
|
Get current contract owner return Address of current contract owner
|
function getOwner() public view returns(address) {
return _owner;
}
| 1,823,401 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "../ics23/ics23.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract AnconProtocol is ICS23 {
struct SubscriptionTier {
address token;
uint256 amount;
uint256 amountStaked;
uint256 includedBlocks;
bytes32 id;
uint256 incentiveBlocksMonthly;
uint256 incentivePercentageMonthly;
uint256 includedBlocksStarted;
uint256 setupFee;
}
address public owner;
address public relayer;
IERC20 public stablecoin;
uint256 chainId = 0;
mapping(bytes => bytes) public accountProofs; //did user-assigned proof key
mapping(address => bytes) public accountByAddrProofs; //proof key-assigned eth address
mapping(bytes => bool) public proofs; //if proof key was submitted to the blockchain
mapping(bytes32 => address) public whitelistedDagGraph;
mapping(bytes32 => SubscriptionTier) public tiers;
mapping(address => SubscriptionTier) public dagGraphSubscriptions;
mapping(address => uint256) public totalHeaderUpdatesByDagGraph;
mapping(address => mapping(address => uint256))
public totalSubmittedByDagGraphUser;
uint256 public seq;
mapping(address => uint256) public nonce;
mapping(bytes32 => bytes) public latestRootHashTable;
mapping(bytes32 => mapping(uint256 => bytes)) public relayerHashTable;
uint256 public INCLUDED_BLOCKS_EPOCH = 200000; // 200 000 chain blocks
event Withdrawn(address indexed paymentAddress, uint256 amount);
event ServiceFeePaid(
address indexed from,
bytes32 indexed tier,
bytes32 indexed moniker,
address token,
uint256 fee
);
event HeaderUpdated(bytes32 indexed moniker);
event ProofPacketSubmitted(
bytes indexed key,
bytes packet,
bytes32 moniker
);
event TierAdded(bytes32 indexed id);
event TierUpdated(
bytes32 indexed id,
address token,
uint256 fee,
uint256 staked,
uint256 includedBlocks
);
event AccountRegistered(
bool enrolledStatus,
bytes key,
bytes value,
bytes32 moniker
);
constructor(
address tokenAddress,
uint256 network,
uint256 starterFee,
uint256 startupFee
) public {
owner = msg.sender;
stablecoin = IERC20(tokenAddress);
chainId = network;
// add tiers
// crear un solo tier `default` Ancon token, starterFee 0.50, blocks, fee y staked en 0
addTier(keccak256("starter"), tokenAddress, starterFee, 0, 100, 0);
addTier(keccak256("startup"), tokenAddress, startupFee, 0, 500, 0);
addTier(keccak256("pro"), tokenAddress, 0, 0, 1000, 150);
/* setTierSettings(
keccak256("pro"),
tokenAddress,
500000000,
1000 ether,
1000
); */
addTier(keccak256("defi"), tokenAddress, 0, 0, 10000, 1500);
addTier(keccak256("luxury"), tokenAddress, 0, 0, 100000, 9000);
}
// getContractIdentifier is used to identify a contract protocol deployed in a specific chain
function getContractIdentifier() public view returns (bytes32) {
return keccak256(abi.encodePacked(chainId, address(this)));
}
// verifyContractIdentifier verifies a nonce is from a specific chain
function verifyContractIdentifier(
uint256 usernonce,
address sender,
bytes32 hash
) public view returns (bool) {
return
keccak256(abi.encodePacked(chainId, address(this))) == hash &&
nonce[sender] == usernonce;
}
function getNonce() public view returns (uint256) {
return nonce[msg.sender];
}
// registerDagGraphTier
function registerDagGraphTier(
bytes32 moniker,
address dagAddress,
bytes32 tier
) public payable {
require(whitelistedDagGraph[moniker] == address(0), "moniker exists");
require(tier == tiers[tier].id, "missing tier");
if(tiers[tier].setupFee > 0){
IERC20 token = IERC20(tiers[tier].token);
require(token.balanceOf(address(msg.sender)) > tiers[tier].setupFee, "no enough balance");
require(
token.transferFrom(
msg.sender,
address(this),
tiers[tier].setupFee
),
"transfer failed for recipient"
);
}
whitelistedDagGraph[moniker] = dagAddress;
dagGraphSubscriptions[dagAddress] = tiers[tier];
}
// updateRelayerHeader updates offchain dag graphs signed by dag graph key pair
function updateRelayerHeader(
bytes32 moniker,
bytes memory rootHash,
uint256 height
) public payable {
require(msg.sender == whitelistedDagGraph[moniker], "invalid user");
SubscriptionTier memory t = dagGraphSubscriptions[msg.sender];
IERC20 token = IERC20(tiers[t.id].token);
require(token.balanceOf(address(msg.sender)) > 0, "no enough balance");
if (t.includedBlocks > 0) {
t.includedBlocks = t.includedBlocks - 1;
} else {
// tier has no more free blocks for this epoch, charge protocol fee
require(
token.transferFrom(
msg.sender,
address(this),
tiers[t.id].amount
),
"transfer failed for recipient"
);
}
// reset tier includede blocks every elapsed epoch
uint256 elapsed = block.number - t.includedBlocksStarted;
if (elapsed > INCLUDED_BLOCKS_EPOCH) {
// must always read from latest tier settings
t.includedBlocks = tiers[t.id].includedBlocks;
t.includedBlocksStarted = block.number;
}
// set hash
relayerHashTable[moniker][height] = rootHash;
latestRootHashTable[moniker] = rootHash;
emit ServiceFeePaid(
msg.sender,
moniker,
t.id,
tiers[t.id].token,
tiers[t.id].amount
);
seq = seq + 1;
totalHeaderUpdatesByDagGraph[msg.sender] =
totalHeaderUpdatesByDagGraph[msg.sender] +
1;
emit HeaderUpdated(moniker);
}
// setPaymentToken sets token used for protocol fees
function setPaymentToken(address tokenAddress) public {
require(owner == msg.sender);
stablecoin = IERC20(tokenAddress);
}
// addTier
function addTier(
bytes32 id,
address tokenAddress,
uint256 amount,
uint256 amountStaked,
uint256 includedBlocks,
uint256 setupFee
) public {
require(owner == msg.sender, "invalid owner");
require(tiers[id].id != id, "tier already in use");
tiers[id] = SubscriptionTier({
token: tokenAddress,
amount: amount,
amountStaked: amountStaked,
includedBlocks: includedBlocks,
id: id,
incentiveBlocksMonthly: 0,
incentivePercentageMonthly: 0,
includedBlocksStarted: block.number,
setupFee: setupFee
});
emit TierAdded(id);
}
// setTierSettings
function setTierSettings(
bytes32 id,
address tokenAddress,
uint256 amount,
uint256 amountStaked,
uint256 includedBlocks,
uint256 setupFee
) public {
require(owner == msg.sender, "invalid owner");
require(tiers[id].id == id, "missing tier");
tiers[id].token = tokenAddress;
tiers[id].amount = amount;
tiers[id].amountStaked = amountStaked;
tiers[id].includedBlocks = includedBlocks;
tiers[id].setupFee = setupFee;
// incentiveBlocksMonthly: 0,
// incentivePercentageMonthly: 0
emit TierUpdated(
id,
tokenAddress,
amount,
amountStaked,
includedBlocks
);
}
// withdraws gas token, must be admin
function withdraw(address payable payee) public {
require(owner == msg.sender);
uint256 b = address(this).balance;
(bool sent, bytes memory data) = payee.call{value: b}("");
}
// withdraws protocol fee token, must be admin
function withdrawToken(address payable payee, address erc20token) public {
require(owner == msg.sender);
uint256 balance = IERC20(erc20token).balanceOf(address(this));
// Transfer tokens to pay service fee
require(IERC20(erc20token).transfer(payee, balance), "transfer failed");
emit Withdrawn(payee, balance);
}
function getProtocolHeader(bytes32 moniker)
public
view
returns (bytes memory)
{
return latestRootHashTable[moniker];
}
function getProof(bytes memory did) public view returns (bytes memory) {
return accountProofs[did];
}
function hasProof(bytes memory key) public view returns (bool) {
return proofs[key];
}
// enrollL2Account registers offchain did user onchain using ICS23 proofs, multi tenant using dag graph moniker
function enrollL2Account(
bytes32 moniker,
bytes memory key,
bytes memory did,
Ics23Helper.ExistenceProof memory proof
) public returns (bool) {
require(keccak256(proof.key) == keccak256(key), "invalid key");
require(verifyProof(moniker, proof), "invalid proof");
require(
keccak256(key) != keccak256(accountProofs[did]),
"user already registered"
);
totalSubmittedByDagGraphUser[whitelistedDagGraph[moniker]][msg.sender] =
totalSubmittedByDagGraphUser[whitelistedDagGraph[moniker]][
msg.sender
] +
1;
accountProofs[(did)] = key;
accountByAddrProofs[msg.sender] = key;
emit AccountRegistered(true, key, did, moniker);
return true;
}
// submitPacketWithProof registers packet onchain using ICS23 proofs, multi tenant using dag graph moniker
function submitPacketWithProof(
bytes32 moniker,
address sender,
Ics23Helper.ExistenceProof memory userProof,
bytes memory key,
bytes memory packet,
Ics23Helper.ExistenceProof memory proof
) external returns (bool) {
// 1. Verify
require(proofs[key] == false, "proof has been submitted (found key)");
require(keccak256(proof.key) == keccak256(key), "invalid key");
require(
keccak256(accountByAddrProofs[sender]) == keccak256(userProof.key),
"invalid user key"
);
require(verifyProof(moniker, userProof), "invalid user proof");
require(verifyProof(moniker, proof));
proofs[key] = true;
totalSubmittedByDagGraphUser[whitelistedDagGraph[moniker]][sender] =
totalSubmittedByDagGraphUser[whitelistedDagGraph[moniker]][
sender
] +
1;
nonce[sender] = nonce[sender] + 1;
// 2. Submit event
emit ProofPacketSubmitted(key, packet, moniker);
return true;
}
// verifies ICS23 proofs, multi tenant using dag graph moniker
function verifyProof(
bytes32 moniker,
Ics23Helper.ExistenceProof memory exProof
) internal view returns (bool) {
// Verify membership
verify(
exProof,
getIavlSpec(),
latestRootHashTable[moniker],
exProof.key,
exProof.value
);
return true;
}
// verifies ICS23 proofs with key and value, multi tenant using dag graph moniker
function verifyProofWithKV(
bytes32 moniker,
bytes memory key,
bytes memory value,
Ics23Helper.ExistenceProof memory exProof
) external view returns (bool) {
// Verify membership
verify(
exProof,
getIavlSpec(),
latestRootHashTable[moniker],
key,
value
);
return true;
}
// calculates root hash
function queryRootCalculation(Ics23Helper.ExistenceProof memory proof)
internal
pure
returns (bytes memory)
{
return bytes(calculate(proof));
}
}
|
verifies ICS23 proofs, multi tenant using dag graph moniker Verify membership
|
function verifyProof(
bytes32 moniker,
Ics23Helper.ExistenceProof memory exProof
) internal view returns (bool) {
verify(
exProof,
getIavlSpec(),
latestRootHashTable[moniker],
exProof.key,
exProof.value
);
return true;
}
| 5,446,931 |
./full_match/5/0x18C68B3adacE08C934408c343BC50a7EDe3F4aD7/sources/project_/contracts/EchoooERC721.sol
|
Returns the average of two signed numbers without overflow. The result is rounded towards zero./ Formula from the book "Hacker's Delight"
|
function average(int256 a, int256 b) internal pure returns (int256) {
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
| 1,859,714 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./common/BaseRelayRecipient.sol";
import "./common/Migratable.sol";
import "./common/NonReentrancy.sol";
import "./common/WeekManaged.sol";
import "./interfaces/IAssetManager.sol";
import "./interfaces/IBuyer.sol";
import "./interfaces/IRegistry.sol";
import "./interfaces/ISeller.sol";
// This contract is not Ownable.
contract Seller is ISeller, WeekManaged, Migratable, NonReentrancy, BaseRelayRecipient {
using SafeERC20 for IERC20;
using SafeMath for uint256;
string public override versionRecipient = "1.0.0";
IRegistry public registry;
struct WithdrawRequest {
uint256 amount;
uint256 time;
bool executed;
}
// who => week => category => WithdrawRequest
mapping(address => mapping(uint256 => mapping(uint8 => WithdrawRequest))) public withdrawRequestMap;
mapping(address => mapping(uint16 => bool)) public userBasket;
struct BasketRequest {
uint16[] assetIndexes;
uint256 time;
bool executed;
}
// who => week => category => BasketRequest
mapping(address => mapping(uint256 => mapping(uint8 => BasketRequest))) public basketRequestMap;
struct PoolInfo {
uint256 weekOfPremium;
uint256 weekOfBonus;
uint256 premiumPerShare;
uint256 bonusPerShare;
}
mapping(uint16 => PoolInfo) public poolInfo;
struct UserBalance {
uint256 currentBalance;
uint256 futureBalance;
}
mapping(address => mapping(uint8 => UserBalance)) public userBalance;
struct UserInfo {
uint256 week;
uint256 premium;
uint256 bonus;
}
mapping(address => UserInfo) public userInfo;
// By category.
mapping(uint8 => uint256) public categoryBalance;
// assetIndex => amount
mapping(uint16 => uint256) public override assetBalance;
struct PayoutInfo {
address toAddress;
uint256 total;
uint256 unitPerShare;
uint256 paid;
bool finished;
}
// assetIndex => payoutId => PayoutInfo
mapping(uint16 => mapping(uint256 => PayoutInfo)) public payoutInfo;
// assetIndex => payoutId
mapping(uint16 => uint256) public payoutIdMap;
// who => assetIndex => payoutId
mapping(address => mapping(uint16 => uint256)) public userPayoutIdMap;
event Update(address indexed who_);
event Deposit(address indexed who_, uint8 indexed category_, uint256 amount_);
event ReduceDeposit(address indexed who_, uint8 indexed category_, uint256 amount_);
event Withdraw(address indexed who_, uint8 indexed category_, uint256 amount_);
event WithdrawReady(address indexed who_, uint8 indexed category_, uint256 amount_);
event ChangeBasket(address indexed who_, uint8 indexed category_);
event ChangeBasketReady(address indexed who_, uint8 indexed category_);
event ClaimPremium(address indexed who_, uint256 amount_);
event ClaimBonus(address indexed who_, uint256 amount_);
event StartPayout(uint16 indexed assetIndex_, uint256 indexed payoutId_);
event SetPayout(uint16 indexed assetIndex_, uint256 indexed payoutId_, address toAddress_, uint256 total_);
event DoPayout(address indexed who_, uint16 indexed assetIndex_, uint256 indexed payoutId_, uint256 amount_);
event FinishPayout(uint16 indexed assetIndex_, uint256 indexed payoutId_);
constructor (IRegistry registry_) public {
registry = registry_;
}
function _timeExtra() internal override view returns(uint256) {
return registry.timeExtra();
}
function _trustedForwarder() internal override view returns(address) {
return registry.trustedForwarder();
}
function _migrationCaller() internal override view returns(address) {
return address(registry);
}
function migrate(uint8 category_) external lock {
uint256 balance = userBalance[_msgSender()][category_].futureBalance;
require(address(migrateTo) != address(0), "Destination not set");
require(balance > 0, "No balance");
userBalance[_msgSender()][category_].currentBalance = 0;
userBalance[_msgSender()][category_].futureBalance = 0;
IERC20(registry.baseToken()).safeTransfer(address(migrateTo), balance);
migrateTo.onMigration(_msgSender(), balance, abi.encodePacked(category_));
}
// Update and pay last week's premium.
function updatePremium(uint16 assetIndex_) external lock {
uint256 week = getCurrentWeek();
require(IBuyer(registry.buyer()).weekToUpdate() == week, "buyer not ready");
require(poolInfo[assetIndex_].weekOfPremium < week, "already updated");
uint256 amount = IBuyer(registry.buyer()).premiumForSeller(assetIndex_);
if (assetBalance[assetIndex_] > 0) {
IERC20(registry.baseToken()).safeTransferFrom(registry.buyer(), address(this), amount);
poolInfo[assetIndex_].premiumPerShare =
amount.mul(registry.UNIT_PER_SHARE()).div(assetBalance[assetIndex_]);
}
poolInfo[assetIndex_].weekOfPremium = week;
}
// Update and pay last week's bonus.
function updateBonus(uint16 assetIndex_, uint256 amount_) external lock override {
require(msg.sender == registry.bonus(), "Only Bonus can call");
uint256 week = getCurrentWeek();
require(poolInfo[assetIndex_].weekOfBonus < week, "already updated");
if (assetBalance[assetIndex_] > 0) {
IERC20(registry.tidalToken()).safeTransferFrom(msg.sender, address(this), amount_);
poolInfo[assetIndex_].bonusPerShare =
amount_.mul(registry.UNIT_PER_SHARE()).div(assetBalance[assetIndex_]);
}
poolInfo[assetIndex_].weekOfBonus = week;
}
function isCategoryLocked(address who_, uint8 category_) public view returns(bool) {
for (uint256 i = 0; i < IAssetManager(registry.assetManager()).getIndexesByCategoryLength(category_); ++i) {
uint16 index = IAssetManager(registry.assetManager()).getIndexesByCategory(category_, i);
uint256 payoutId = payoutIdMap[index];
if (payoutId > 0 && !payoutInfo[index][payoutId].finished && userBasket[who_][index]) return true;
}
return false;
}
function isAssetLocked(uint16 assetIndex_) external override view returns(bool) {
uint256 payoutId = payoutIdMap[assetIndex_];
return payoutId > 0 && !payoutInfo[assetIndex_][payoutId].finished;
}
function isBasketLocked(uint16[] memory basketIndexes_) public view returns(bool) {
for (uint256 i = 0; i < basketIndexes_.length; ++i) {
uint16 assetIndex = basketIndexes_[i];
uint256 payoutId = payoutIdMap[assetIndex];
if (payoutId > 0 && !payoutInfo[assetIndex][payoutId].finished) return true;
}
return false;
}
function hasIndex(uint16[] memory basketIndexes_, uint16 index_) public pure returns(bool) {
for (uint256 i = 0; i < basketIndexes_.length; ++i) {
if (basketIndexes_[i] == index_) return true;
}
return false;
}
function changeBasket(uint8 category_, uint16[] calldata basketIndexes_) external {
require(!isCategoryLocked(_msgSender(), category_), "Asset locked");
require(!isBasketLocked(basketIndexes_), "Is basket locked");
if (isFirstTime(_msgSender())) {
update(_msgSender());
}
require(userInfo[_msgSender()].week == getCurrentWeek(), "Not updated yet");
if (userBalance[_msgSender()][category_].currentBalance == 0) {
// Change now.
for (uint256 i = 0;
i < IAssetManager(registry.assetManager()).getIndexesByCategoryLength(category_);
++i) {
uint16 index = uint16(IAssetManager(registry.assetManager()).getIndexesByCategory(category_, i));
bool has = hasIndex(basketIndexes_, index);
if (has && !userBasket[_msgSender()][index]) {
userBasket[_msgSender()][index] = true;
} else if (!has && userBasket[_msgSender()][index]) {
userBasket[_msgSender()][index] = false;
}
}
} else {
// Change later.
BasketRequest memory request;
request.assetIndexes = basketIndexes_;
request.time = getNow();
request.executed = false;
// One request per week per category.
basketRequestMap[_msgSender()][getUnlockWeek()][category_] = request;
}
emit ChangeBasket(_msgSender(), category_);
}
function changeBasketReady(address who_, uint8 category_) external {
BasketRequest storage request = basketRequestMap[who_][getCurrentWeek()][category_];
require(!isCategoryLocked(who_, category_), "Asset locked");
require(userInfo[who_].week == getCurrentWeek(), "Not updated yet");
require(!request.executed, "already executed");
require(request.time > 0, "No request");
uint256 unlockTime = getUnlockTime(request.time);
require(getNow() > unlockTime, "Not ready to change yet");
uint256 currentBalance = userBalance[who_][category_].currentBalance;
for (uint256 i = 0;
i < IAssetManager(registry.assetManager()).getIndexesByCategoryLength(category_);
++i) {
uint16 index = uint16(IAssetManager(registry.assetManager()).getIndexesByCategory(category_, i));
bool has = hasIndex(request.assetIndexes, index);
if (has && !userBasket[who_][index]) {
userBasket[who_][index] = true;
assetBalance[index] = assetBalance[index].add(
currentBalance);
} else if (!has && userBasket[who_][index]) {
userBasket[who_][index] = false;
assetBalance[index] = assetBalance[index].sub(
currentBalance);
}
}
request.executed = true;
emit ChangeBasketReady(_msgSender(), category_);
}
// Called for every user every week.
function update(address who_) public override {
// Update user's last week's premium and bonus.
uint256 week = getCurrentWeek();
require(userInfo[who_].week < week, "Already updated");
uint16 index;
// Assert if premium or bonus not updated, or user already updated.
for (index = 0;
index < IAssetManager(registry.assetManager()).getAssetLength();
++index) {
require(poolInfo[index].weekOfPremium == week &&
poolInfo[index].weekOfBonus == week, "Not ready");
}
uint8 category;
// For every asset
for (index = 0;
index < IAssetManager(registry.assetManager()).getAssetLength();
++index) {
category = IAssetManager(registry.assetManager()).getAssetCategory(index);
uint256 currentBalance = userBalance[who_][category].currentBalance;
uint256 futureBalance = userBalance[who_][category].futureBalance;
// Update asset balance if no claims.
if (userBasket[who_][index]) {
// Update bonus.
userInfo[who_].bonus = userInfo[who_].bonus.add(currentBalance.mul(
poolInfo[index].bonusPerShare).div(registry.UNIT_PER_SHARE()));
if (!isCategoryLocked(who_, category)) {
// Update premium.
userInfo[who_].premium = userInfo[who_].premium.add(currentBalance.mul(
poolInfo[index].premiumPerShare).div(registry.UNIT_PER_SHARE()));
assetBalance[index] = assetBalance[index].add(futureBalance).sub(currentBalance);
}
}
}
// Update user balance and category balance if no claims.
for (category = 0;
category < IAssetManager(registry.assetManager()).getCategoryLength();
++category) {
if (!isCategoryLocked(who_, category)) {
uint256 currentBalance = userBalance[who_][category].currentBalance;
uint256 futureBalance = userBalance[who_][category].futureBalance;
userBalance[who_][category].currentBalance = futureBalance;
categoryBalance[category] = categoryBalance[category].add(
futureBalance).sub(currentBalance);
}
}
// Update week.
userInfo[who_].week = week;
emit Update(who_);
}
function isFirstTime(address who_) public view returns(bool) {
return userInfo[who_].week == 0;
}
function deposit(uint8 category_, uint256 amount_) external lock {
require(!registry.depositPaused(), "Deposit paused");
require(!isCategoryLocked(_msgSender(), category_), "Asset locked");
if (isFirstTime(_msgSender())) {
update(_msgSender());
}
require(userInfo[_msgSender()].week == getCurrentWeek(), "Not updated yet");
IERC20(registry.baseToken()).safeTransferFrom(_msgSender(), address(this), amount_);
userBalance[_msgSender()][category_].futureBalance = userBalance[_msgSender()][category_].futureBalance.add(amount_);
emit Deposit(_msgSender(), category_, amount_);
}
function reduceDeposit(uint8 category_, uint256 amount_) external lock {
// Even asset locked, user can still reduce.
require(userInfo[_msgSender()].week == getCurrentWeek(), "Not updated yet");
require(amount_ <= userBalance[_msgSender()][category_].futureBalance.sub(
userBalance[_msgSender()][category_].currentBalance), "Not enough future balance");
IERC20(registry.baseToken()).safeTransfer(_msgSender(), amount_);
userBalance[_msgSender()][category_].futureBalance = userBalance[_msgSender()][category_].futureBalance.sub(amount_);
emit ReduceDeposit(_msgSender(), category_, amount_);
}
function withdraw(uint8 category_, uint256 amount_) external {
require(!isCategoryLocked(_msgSender(), category_), "Asset locked");
require(userInfo[_msgSender()].week == getCurrentWeek(), "Not updated yet");
require(amount_ > 0, "Requires positive amount");
require(amount_ <= userBalance[_msgSender()][category_].currentBalance, "Not enough user balance");
WithdrawRequest memory request;
request.amount = amount_;
request.time = getNow();
request.executed = false;
withdrawRequestMap[_msgSender()][getUnlockWeek()][category_] = request;
emit Withdraw(_msgSender(), category_, amount_);
}
function withdrawReady(address who_, uint8 category_) external lock {
WithdrawRequest storage request = withdrawRequestMap[who_][getCurrentWeek()][category_];
require(!isCategoryLocked(who_, category_), "Asset locked");
require(userInfo[who_].week == getCurrentWeek(), "Not updated yet");
require(!request.executed, "already executed");
require(request.time > 0, "No request");
uint256 unlockTime = getUnlockTime(request.time);
require(getNow() > unlockTime, "Not ready to withdraw yet");
IERC20(registry.baseToken()).safeTransfer(who_, request.amount);
for (uint256 i = 0;
i < IAssetManager(registry.assetManager()).getIndexesByCategoryLength(category_);
++i) {
uint16 index = IAssetManager(registry.assetManager()).getIndexesByCategory(category_, i);
// Only process assets in my basket.
if (userBasket[who_][index]) {
assetBalance[index] = assetBalance[index].sub(request.amount);
}
}
userBalance[who_][category_].currentBalance = userBalance[who_][category_].currentBalance.sub(request.amount);
userBalance[who_][category_].futureBalance = userBalance[who_][category_].futureBalance.sub(request.amount);
categoryBalance[category_] = categoryBalance[category_].sub(request.amount);
request.executed = true;
emit WithdrawReady(_msgSender(), category_, request.amount);
}
function claimPremium() external lock {
IERC20(registry.baseToken()).safeTransfer(_msgSender(), userInfo[_msgSender()].premium);
emit ClaimPremium(_msgSender(), userInfo[_msgSender()].premium);
userInfo[_msgSender()].premium = 0;
}
function claimBonus() external lock {
IERC20(registry.tidalToken()).safeTransfer(_msgSender(), userInfo[_msgSender()].bonus);
emit ClaimBonus(_msgSender(), userInfo[_msgSender()].bonus);
userInfo[_msgSender()].bonus = 0;
}
function startPayout(uint16 assetIndex_, uint256 payoutId_) external override {
require(msg.sender == registry.committee(), "Only commitee can call");
require(payoutId_ == payoutIdMap[assetIndex_] + 1, "payoutId should be increasing");
payoutIdMap[assetIndex_] = payoutId_;
emit StartPayout(assetIndex_, payoutId_);
}
function setPayout(uint16 assetIndex_, uint256 payoutId_, address toAddress_, uint256 total_) external override {
require(msg.sender == registry.committee(), "Only commitee can call");
require(payoutId_ == payoutIdMap[assetIndex_], "payoutId should be started");
require(payoutInfo[assetIndex_][payoutId_].toAddress == address(0), "already set");
require(total_ <= assetBalance[assetIndex_], "More than asset");
// total_ can be 0.
payoutInfo[assetIndex_][payoutId_].toAddress = toAddress_;
payoutInfo[assetIndex_][payoutId_].total = total_;
payoutInfo[assetIndex_][payoutId_].unitPerShare = total_.mul(registry.UNIT_PER_SHARE()).div(assetBalance[assetIndex_]);
payoutInfo[assetIndex_][payoutId_].paid = 0;
payoutInfo[assetIndex_][payoutId_].finished = false;
emit SetPayout(assetIndex_, payoutId_, toAddress_, total_);
}
// This function can be called by anyone.
function doPayout(address who_, uint16 assetIndex_) external {
require(userBasket[who_][assetIndex_], "must be in basket");
uint256 payoutId = payoutIdMap[assetIndex_];
require(payoutInfo[assetIndex_][payoutId].toAddress != address(0), "not set");
require(userPayoutIdMap[who_][assetIndex_] < payoutId, "Already paid");
userPayoutIdMap[who_][assetIndex_] = payoutId;
if (payoutInfo[assetIndex_][payoutId].finished) {
// In case someone paid for the difference.
return;
}
uint8 category = IAssetManager(registry.assetManager()).getAssetCategory(assetIndex_);
uint256 amountToPay = userBalance[who_][category].currentBalance.mul(
payoutInfo[assetIndex_][payoutId].unitPerShare).div(registry.UNIT_PER_SHARE());
userBalance[who_][category].currentBalance = userBalance[who_][category].currentBalance.sub(amountToPay);
userBalance[who_][category].futureBalance = userBalance[who_][category].futureBalance.sub(amountToPay);
categoryBalance[category] = categoryBalance[category].sub(amountToPay);
// Reduce asset balance of all assets in the user's basket.
for (uint256 i = 0;
i < IAssetManager(registry.assetManager()).getIndexesByCategoryLength(category);
++i) {
uint16 index = uint16(IAssetManager(registry.assetManager()).getIndexesByCategory(category, i));
if (userBasket[who_][index]) {
assetBalance[index] = assetBalance[index].sub(amountToPay);
}
}
payoutInfo[assetIndex_][payoutId].paid = payoutInfo[assetIndex_][payoutId].paid.add(amountToPay);
emit DoPayout(who_, assetIndex_, payoutId, amountToPay);
}
// This function can be called by anyone as long as he will pay for the difference.
function finishPayout(uint16 assetIndex_, uint256 payoutId_) external lock {
require(payoutId_ <= payoutIdMap[assetIndex_], "payoutId should be valid");
require(!payoutInfo[assetIndex_][payoutId_].finished, "already finished");
if (payoutInfo[assetIndex_][payoutId_].paid < payoutInfo[assetIndex_][payoutId_].total) {
// In case you wanna pay for the difference.
IERC20(registry.baseToken()).safeTransferFrom(
msg.sender,
address(this),
payoutInfo[assetIndex_][payoutId_].total.sub(payoutInfo[assetIndex_][payoutId_].paid));
payoutInfo[assetIndex_][payoutId_].paid = payoutInfo[assetIndex_][payoutId_].total;
}
IERC20(registry.baseToken()).safeTransfer(payoutInfo[assetIndex_][payoutId_].toAddress,
payoutInfo[assetIndex_][payoutId_].total);
payoutInfo[assetIndex_][payoutId_].finished = true;
emit FinishPayout(assetIndex_, payoutId_);
}
function getPendingBasket(address who_, uint8 category_, uint256 week_) external view returns(uint16[] memory) {
BasketRequest storage request = basketRequestMap[who_][week_][category_];
return request.assetIndexes;
}
}
|
Called for every user every week. Update user's last week's premium and bonus. Assert if premium or bonus not updated, or user already updated. Update asset balance if no claims. Update bonus. Update premium.
|
function update(address who_) public override {
uint256 week = getCurrentWeek();
require(userInfo[who_].week < week, "Already updated");
uint16 index;
for (index = 0;
index < IAssetManager(registry.assetManager()).getAssetLength();
++index) {
require(poolInfo[index].weekOfPremium == week &&
poolInfo[index].weekOfBonus == week, "Not ready");
}
uint8 category;
index < IAssetManager(registry.assetManager()).getAssetLength();
++index) {
category = IAssetManager(registry.assetManager()).getAssetCategory(index);
uint256 currentBalance = userBalance[who_][category].currentBalance;
uint256 futureBalance = userBalance[who_][category].futureBalance;
if (userBasket[who_][index]) {
userInfo[who_].bonus = userInfo[who_].bonus.add(currentBalance.mul(
poolInfo[index].bonusPerShare).div(registry.UNIT_PER_SHARE()));
if (!isCategoryLocked(who_, category)) {
userInfo[who_].premium = userInfo[who_].premium.add(currentBalance.mul(
poolInfo[index].premiumPerShare).div(registry.UNIT_PER_SHARE()));
assetBalance[index] = assetBalance[index].add(futureBalance).sub(currentBalance);
}
}
}
category < IAssetManager(registry.assetManager()).getCategoryLength();
++category) {
if (!isCategoryLocked(who_, category)) {
uint256 currentBalance = userBalance[who_][category].currentBalance;
uint256 futureBalance = userBalance[who_][category].futureBalance;
userBalance[who_][category].currentBalance = futureBalance;
categoryBalance[category] = categoryBalance[category].add(
futureBalance).sub(currentBalance);
}
}
emit Update(who_);
}
| 13,110,667 |
./full_match/1/0xff368E106EA8782FaB6B2D4AD69739a60C66400E/sources/contracts/Balancer/MarketMaker.sol
|
Get the ticks from price range return minTick The minimum tick return maxTick The maximum tick/
|
function getTicks(
uint256 minPrice,
uint256 maxPrice,
uint24 poolFee
) internal view returns (int24 minTick, int24 maxTick) {
int24 tickSpacing = liquidityHelper.getTickSpacing(
token0,
token1,
poolFee
);
uint8 decimals = sweep.decimals();
minTick = liquidityHelper.getTickFromPrice(
minPrice,
decimals,
tickSpacing,
flag
);
maxTick = liquidityHelper.getTickFromPrice(
maxPrice,
decimals,
tickSpacing,
flag
);
(minTick, maxTick) = minTick < maxTick
? (minTick, maxTick)
: (maxTick, minTick);
}
| 3,204,989 |
./full_match/1/0x92E79B2779460acd23548Af27a175467b32561b0/sources/ERC20.sol
|
Atomically increases the allowance granted to `spender` by the caller. Emits a {Approval} event. @solidity memory-safe-assembly Compute the allowance slot and load its value. Add to the allowance. Revert upon overflow.
|
function increaseAllowance(
address spender,
uint256 difference
) public virtual returns (bool) {
assembly {
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, caller())
let allowanceSlot := keccak256(0x0c, 0x34)
let allowanceBefore := sload(allowanceSlot)
let allowanceAfter := add(allowanceBefore, difference)
if lt(allowanceAfter, allowanceBefore) {
revert(0x1c, 0x04)
}
log3(
0x00,
0x20,
_APPROVAL_EVENT_SIGNATURE,
caller(),
shr(96, mload(0x2c))
)
}
return true;
}
| 3,876,000 |
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.22 <0.9.0;
/**
* Migrated from https://github.com/skfarhat/ethbnb
*/
import "../common/Version.sol";
import "../common/Frozen.sol";
contract BlockchainBNB is Version, Frozen {
bytes32 constant private ZERO_BYTES = bytes32(0);
address constant private ZERO_ADDRESS = address(0);
uint constant private SECONDS_PER_DAY = 3600 * 24;
uint constant private HEAD = 0;
uint constant private JUNK = 2^256-1; // We assume there won't be that many bookings
int public constant NOT_FOUND = -1;
int public constant BOOK_CONFLICT = -2;
enum Country {
AF, AX, AL, DZ, AS, AD, AO, AI, AG, AR, AM, AW, AU, AT, AZ, BS, BH,
BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BA, BW, BV, BR, VG, BN, BG, BF,
BI, TC, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD,
CK, CR, CI, HR, CU, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GB, GQ, ER,
EE, ET, EU, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI,
GR, GL, GD, GP, GU, GT, GW, GN, GY, HT, HM, HN, HK, HU, IS, IN, IO,
ID, IR, IQ, IE, IL, IT, JM, JP, JO, KZ, KE, KI, KW, KG, LA, LV, LB,
LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR,
MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, NA, NR, NP, AN, NL, NC,
PG, NZ, NI, NE, NG, NU, NF, KP, MP, NO, OM, PK, PW, PS, PA, PY, PE,
PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, SH, KN, LC, PM, VC, WS, SM,
GS, ST, SA, SN, CS, RS, SC, SL, SG, SK, SI, SB, SO, ZA, KR, ES, LK,
SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN,
TR, TM, TV, UG, UA, AE, US, UY, UM, VI, UZ, VU, VA, VE, VN, WF, EH,
YE, ZM, ZW
}
struct Node {
/// Booking's start date in seconds
uint fromDate;
/// Booking's end date in seconds
uint toDate;
uint bid;
uint next;
}
struct Listing {
uint lid;
address owner;
Country country;
string location;
uint price;
uint balance;
string imageCID;
string imageCIDSource;
address booker;
}
struct Account {
address payable owner;
string name;
uint dateCreated;
/**
* Account's average rating (out of 5) can be computed as
* totalScore / totalRatings
*/
uint totalScore;
uint nRatings;
}
struct Booking {
uint bid;
uint lid;
address guestAddr;
address hostAddr;
/**
* Rating assigned to the owner by the guest
* defaults to 0 which means nothing was set
*/
uint ownerRating;
/**
* Rating assigned to the guest by the owner
* defaults to 0 which means nothing was set
*/
uint guestRating;
/**
* When a booking is made, the listing balance (staked by the host)
* along with the value staked by the guest are added to the balance here.
* The listing balance is obviously decreased.
*/
uint256 balance;
}
// =======================================================================
// MEMBER VARIABLES
// =======================================================================
event Log(string functionName, string msg);
event Error(int code);
// Account events
event CreateAccountEvent(address from);
event UpdateAccountEvent(address from);
event DeleteAccountEvent(address from);
// Listing events
event CreateListingEvent(address from, uint lid);
event UpdateListingEvent(address from, uint lid);
event DeleteListingEvent(address from, uint lid);
// Booking events
event BookingComplete(address from, uint bid);
event BookingCancelled(address from, uint bid);
event RatingComplete(address from, uint bid, uint stars);
event Booked(uint bid);
event Cancelled(uint bid);
event Log(uint, uint);
struct BlockchainBNBStorage {
uint nextPos;
/**
* Listings will have incrementing Ids starting from 1
*/
uint nextListingId;
/**
* Bookings will have incrementing Ids starting from 1
*/
uint nextBookingId;
mapping (uint => Node) nodes;
/** Store all created listings */
mapping(uint => Listing) listings;
/** Stores accounts */
mapping(address => Account) accounts;
/** Stores bookings */
mapping(uint => Booking) bookings;
}
BlockchainBNBStorage bnbStorage;
constructor() {
blockchainBNBStorage().nextPos = 1;
blockchainBNBStorage().nextListingId = 1;
blockchainBNBStorage().nextBookingId = 1;
blockchainBNBStorage().nodes[HEAD].next = HEAD; // (implicit since HEAD = 0)
blockchainBNBStorage().nodes[JUNK].next = JUNK;
}
function blockchainBNBStorage()
internal
pure
returns (BlockchainBNBStorage storage ds)
{
bytes32 position = keccak256("BlockchainBNB.storage");
assembly {
ds.slot := position
}
}
// =======================================================================
// FUNCTIONS
// =======================================================================
modifier accountExists() {
require(blockchainBNBStorage().accounts[msg.sender].owner == msg.sender, 'Invalid account address');
_;
}
modifier validBooking(uint bid) {
require(blockchainBNBStorage().bookings[bid].bid == bid, 'Invalid booking identifier');
_;
}
modifier listingExists(uint lid) {
require(blockchainBNBStorage().accounts[msg.sender].owner == msg.sender, 'Invalid account address');
require(blockchainBNBStorage().listings[lid].lid == lid, 'Invalid listing identifier');
_;
}
modifier onlyListingHost(uint lid) {
require(blockchainBNBStorage().listings[lid].owner == msg.sender, 'Only listing host can change it');
_;
}
function createAccount(string memory name) public {
blockchainBNBStorage().accounts[msg.sender] = Account({
owner : payable(msg.sender),
name : name,
dateCreated : block.timestamp,
totalScore: 0,
nRatings: 0
});
emit CreateAccountEvent(msg.sender);
}
function hasAccount() public view returns (bool) {
return blockchainBNBStorage().accounts[msg.sender].owner == msg.sender;
}
function getAccountAll(address owner) public view
returns (string memory name, uint dateCreated, uint totalScore, uint nRatings) {
require(blockchainBNBStorage().accounts[owner].owner == owner, 'Invalid account address');
Account memory account = blockchainBNBStorage().accounts[owner];
return (account.name, account.dateCreated, account.totalScore, account.nRatings);
}
function getListingAll(uint lid) public listingExists(lid) view
returns (address owner, uint price, string memory location, Country country, uint256 balance,
string memory imageCID, string memory imageCIDSource) {
Listing storage l = blockchainBNBStorage().listings[lid];
return (l.owner, l.price, l.location, l.country, l.balance, l.imageCID, l.imageCIDSource);
}
/**
* Creates a new listing for the message sender
* and returns the Id of the created listing
*
* When the listing create the smart-contract will have had the 2xprice amount
* added to its balance.
*/
function createListing(Country country, string memory location, uint price)
public payable accountExists() {
// Note: enforce a maximum number of listings per user?
blockchainBNBStorage().listings[blockchainBNBStorage().nextListingId] = Listing({
lid : blockchainBNBStorage().nextListingId,
owner: msg.sender,
country: country,
location: location,
price: price,
balance: msg.value,
imageCID: '',
imageCIDSource: '',
booker: msg.sender
});
emit CreateListingEvent(msg.sender, blockchainBNBStorage().nextListingId++);
}
/**
* Book a listing
*
* @param lid id of the listing to be booked
* @param fromDate start date of the booking in seconds
* @param nbOfDays number of days for which the booking will be made
*/
function bookListing(uint lid, uint fromDate, uint nbOfDays)
public payable listingExists(lid) {
// TODO: cap the number of booked days to 30 or so
Listing storage listing = blockchainBNBStorage().listings[lid];
address payable guest = payable(msg.sender);
uint256 stake = 2 * listing.price * nbOfDays;
uint toDate = fromDate + nbOfDays * SECONDS_PER_DAY;
require(listing.owner != guest, 'Owner cannot book their own listing');
// Ensure both guest and host have staked the same
require(msg.value >= stake, 'Guest must stake twice the price');
require(listing.balance >= stake, 'Listing must have stake amount in its balance');
// Try to book.
// If successful, create a booking event with the balance amount
// If unsuccessful, refund the stake to guest
int res = book(blockchainBNBStorage().nextBookingId++, fromDate, toDate);
if (res >= 0) {
uint bid = uint(res);
// Save the booking
blockchainBNBStorage().bookings[bid] = Booking({
bid: bid,
lid: lid,
hostAddr: blockchainBNBStorage().listings[lid].owner,
guestAddr: guest,
ownerRating: 0,
guestRating: 0,
// Add the amounts staked by the guest
// and by the host to the booking balance
balance: 2 * stake
});
// Decrement the listing balance
listing.balance -= stake;
// Refund any excess to the guest
guest.transfer(msg.value - stake);
emit BookingComplete(msg.sender, bid);
} else {
// Refund all Ether provided if the booking failed
guest.transfer(msg.value);
}
}
function setListing(uint lid, uint price, string memory location, Country country)
public listingExists(lid) onlyListingHost(lid) {
Listing storage listing = blockchainBNBStorage().listings[lid];
listing.location = location;
listing.price = price;
listing.country = country;
emit UpdateListingEvent(msg.sender, lid);
}
function setListingImage(uint lid, string memory cid, string memory cidSource)
public listingExists(lid) onlyListingHost(lid) {
Listing storage listing = blockchainBNBStorage().listings[lid];
listing.imageCID = cid;
listing.imageCIDSource = cidSource;
emit UpdateListingEvent(msg.sender, lid);
}
/**
* Returns the listing balance to its owner and deletes the listing
*
* Only if there are no active bookings.
*
* @param lid id of the listing to be deleted
*/
function deleteListing(uint lid) public listingExists(lid) onlyListingHost(lid) {
// Check that there are no active bookings before we proceed
Listing storage listing = blockchainBNBStorage().listings[lid];
require(false == hasActiveBookings(), 'Cannot delete listing with active bookings');
// Return listing balance to its owner
uint toReturn = listing.balance;
listing.balance = 0;
blockchainBNBStorage().accounts[listing.owner].owner.transfer(toReturn);
// Delete listing's storage
delete blockchainBNBStorage().listings[lid];
emit DeleteListingEvent(msg.sender, lid);
}
function depositIntoListing(uint lid)
public payable
listingExists(lid)
onlyListingHost(lid)
{
Listing storage listing = blockchainBNBStorage().listings[lid];
listing.balance += msg.value;
}
function withdrawFromListing(uint lid, uint amount)
public
listingExists(lid)
onlyListingHost(lid)
{
Listing storage listing = blockchainBNBStorage().listings[lid];
require(amount <= listing.balance, 'Cannot withdraw more than listing balance');
listing.balance -= amount;
blockchainBNBStorage().accounts[blockchainBNBStorage().listings[lid].owner].owner.transfer(amount);
}
/**
* Invoked by the guest of a booking after the booking end,
* confirming the host fulfilled their obligations, and
* releasing funds held in escrow.
*
* @param bid id of the booking
*/
function fulfilBooking(uint bid) public validBooking(bid) {
Booking storage booking = blockchainBNBStorage().bookings[bid];
uint lid = booking.lid;
address guest = booking.guestAddr;
address host = booking.hostAddr;
(, uint toDate) = getBookingDates(bid);
require(msg.sender == guest, 'Only guest can call fulfilBooking');
require(toDate <= block.timestamp, 'Cannot fulfil booking before end date');
// Fund Release:
// Guest receives: booking.balance
// Listing receives: 2 x booking.balance
// Owner: booking.balance
//
uint256 amount = booking.balance / 4;
booking.balance = 0;
blockchainBNBStorage().listings[lid].balance += amount * 2;
blockchainBNBStorage().accounts[host].owner.transfer(amount);
blockchainBNBStorage().accounts[guest].owner.transfer(amount);
}
/**
* Rate the booking 1-5 stars
*
* The function checks the msg.sender and validates
* they were either owner or guest in the booking.
*
* If they were not, a PermissionDenied event is emitted.
*
* @param bid the identifier for their booking, this
* coupled with msg.sender is enough to determine
* the person being rated
* @param stars unsigned integer between 1 and 5, anything else
* will emit an error
*/
function rate(uint bid, uint stars) public validBooking(bid) {
require(stars >= 1 && stars <= 5, 'Stars arg must be in [1,5]');
Booking storage booking = blockchainBNBStorage().bookings[bid];
require(booking.guestAddr == msg.sender || booking.hostAddr == msg.sender, 'Sender not participated in booking');
(, uint toDate) = getBookingDates(bid);
require(toDate <= block.timestamp, 'Cannot rate a booking before it ends');
if (booking.guestAddr == msg.sender) {
// The guest is rating the owner
require(booking.ownerRating == 0, 'Owner already rated, cannot re-rate');
// Assign the rating and adjust their account
booking.ownerRating = stars;
blockchainBNBStorage().accounts[booking.hostAddr].totalScore += stars;
blockchainBNBStorage().accounts[booking.hostAddr].nRatings++;
}
else if (booking.hostAddr == msg.sender) {
// The owner is rating the guest
require(booking.guestRating == 0, 'Guest already rated, cannot re-rate');
// Adding the rating and adjust their account
booking.guestRating = stars;
blockchainBNBStorage().accounts[booking.guestAddr].totalScore += stars;
blockchainBNBStorage().accounts[booking.guestAddr].nRatings++;
}
emit RatingComplete(msg.sender, bid, stars);
}
/**
* Cancel a booking
*
* @param bid id of the booking to be cancelled
*/
function cancelBooking(uint bid) public validBooking(bid) {
Booking storage booking = blockchainBNBStorage().bookings[bid];
require(
msg.sender == booking.hostAddr ||
msg.sender == booking.guestAddr,
'Only Guest or Host can cancel a booking'
);
int res = cancel(bid);
if (res >= 0) {
delete blockchainBNBStorage().bookings[bid];
emit BookingCancelled(msg.sender, bid);
}
}
function getBookingAll(uint bid) public view
validBooking(bid)
returns (uint lid, address guest, address host, uint fromDate, uint toDate)
{
Booking storage booking = blockchainBNBStorage().bookings[bid];
(uint fromDate1, uint toDate1) = getDates(bid);
return (booking.lid, booking.guestAddr, booking.hostAddr, fromDate1, toDate1);
}
function getBookingDates(uint bid) public view
validBooking(bid)
returns (uint fromDate, uint toDate)
{
return getDates(bid);
}
function getNextPos() public view returns (uint)
{
return blockchainBNBStorage().nextPos;
}
function setNextPos(uint pos) public
{
blockchainBNBStorage().nextPos = pos;
}
function getListingId(uint pos) public view returns (Node memory)
{
return blockchainBNBStorage().nodes[pos];
}
/// The list is empty if the HEAD node points to itself
function isEmpty() public view returns (bool)
{
return blockchainBNBStorage().nodes[HEAD].next == HEAD;
}
function createLink(uint fromNode, uint toNode) private
{
blockchainBNBStorage().nodes[fromNode].next = toNode;
}
function _printAll() public
{
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
emit Log(blockchainBNBStorage().nodes[curr].fromDate, blockchainBNBStorage().nodes[curr].toDate);
curr = blockchainBNBStorage().nodes[curr].next;
}
}
function _printJunk() public
{
if (!junkIsEmpty()) {
uint curr = blockchainBNBStorage().nodes[JUNK].next;
while (curr != JUNK) {
emit Log(blockchainBNBStorage().nodes[curr].fromDate, blockchainBNBStorage().nodes[curr].toDate);
curr = blockchainBNBStorage().nodes[curr].next;
}
}
}
/// Returns true if junk is initialised: if it points to itself
function junkNotInitialised() private view returns (bool)
{
return blockchainBNBStorage().nodes[JUNK].next == 0;
}
function junkIsEmpty() private view returns (bool)
{
return junkNotInitialised() || blockchainBNBStorage().nodes[JUNK].next == JUNK;
}
// Adds the provided node to junk
function addJunk(uint node) private
{
require(node != JUNK, 'Cannot add provided node to Junk');
if (junkNotInitialised()) {
blockchainBNBStorage().nodes[JUNK].next = JUNK;
}
createLink(node, blockchainBNBStorage().nodes[JUNK].next);
createLink(JUNK, node);
}
/// Pops the junk node at head of list and returns its index
function popJunk() private returns (uint)
{
uint ret = blockchainBNBStorage().nodes[JUNK].next;
createLink(JUNK, blockchainBNBStorage().nodes[ret].next);
return ret;
}
/// Free all junk storage kept for reuse
function freeJunk() public
{
while (!junkIsEmpty()) {
uint idx = popJunk();
delete blockchainBNBStorage().nodes[idx];
}
}
/// Removes node from the list. Requires the prevNode be provided.
function removeNode(uint node, uint prevNode) private
{
createLink(prevNode, blockchainBNBStorage().nodes[node].next);
addJunk(node);
}
/// Returns the next available position and updates it
function useNextPos() public returns (uint pos)
{
if (junkIsEmpty()) {
return blockchainBNBStorage().nextPos++;
} else {
// Recycle node
return popJunk();
}
}
function newNode(uint prevNode, uint nextNode, uint bid, uint fromDate, uint toDate) private
{
uint nextPos = useNextPos();
Node memory n = Node({
fromDate: fromDate,
toDate: toDate,
bid: bid,
next: nextNode
});
createLink(prevNode, nextPos);
createLink(nextPos, nextNode); // redundant, but there for readability
blockchainBNBStorage().nodes[nextPos] = n;
}
/// Called by book function
///
/// - Creates a new LinkedList node
/// - Emits Booking event
/// - Updates nextBid
function newBook(uint prevNode, uint nextNode, uint bid, uint fromDate, uint toDate)
private returns (uint)
{
require(toDate > fromDate, 'fromDate must be less than toDate');
newNode(prevNode, nextNode, bid, fromDate, toDate);
emit Booked(bid);
return bid;
}
function book(uint bid, uint fromDate, uint toDate) public returns (int)
{
require(fromDate < toDate, 'Invalid dates provided');
uint prev = HEAD;
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
uint currFrom = blockchainBNBStorage().nodes[curr].fromDate;
uint currTo = blockchainBNBStorage().nodes[curr].toDate;
if (fromDate >= currTo) {
return int(newBook(prev, curr, bid, fromDate, toDate));
} else if (toDate <= currFrom) {
prev = curr;
curr = blockchainBNBStorage().nodes[curr].next;
} else {
return BOOK_CONFLICT;
}
}
return int(newBook(prev, HEAD, bid, fromDate, toDate));
}
function cancel(uint bid) public returns (int)
{
uint prev = HEAD;
uint curr = blockchainBNBStorage().nodes[prev].next;
// Find node with matching bid, then remove it
while (curr != HEAD) {
if (blockchainBNBStorage().nodes[curr].bid == bid) {
removeNode(curr, prev);
emit Cancelled(bid);
return int(bid);
}
prev = curr;
curr = blockchainBNBStorage().nodes[curr].next;
}
return NOT_FOUND;
}
function cancelPastBookings() public
{
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
if (blockchainBNBStorage().nodes[curr].toDate < block.timestamp) {
break;
}
curr = blockchainBNBStorage().nodes[curr].next;
}
// Add all bookings starting from curr to junk
while (curr != HEAD) {
addJunk(curr);
curr = blockchainBNBStorage().nodes[curr].next;
}
}
/// Return index of found id
function find(uint id) public view returns (int) {
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
if (blockchainBNBStorage().nodes[curr].bid == id) {
return int(curr);
}
curr = blockchainBNBStorage().nodes[curr].next;
}
return NOT_FOUND;
}
function hasActiveBookings() public view returns (bool)
{
uint first = blockchainBNBStorage().nodes[HEAD].next;
return blockchainBNBStorage().nodes[first].toDate >= block.timestamp;
}
function getDates(uint id) public view returns (uint fromDate, uint toDate) {
int idx = find(id);
require(idx != NOT_FOUND, 'Entry not found');
Node memory node = blockchainBNBStorage().nodes[uint(idx)];
return (node.fromDate, node.toDate);
}
}
|
Return index of found id
|
function find(uint id) public view returns (int) {
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
if (blockchainBNBStorage().nodes[curr].bid == id) {
return int(curr);
}
curr = blockchainBNBStorage().nodes[curr].next;
}
return NOT_FOUND;
}
| 14,068,375 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ERC721URIStorage} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import {NativeMetaTransaction} from "../../common/NativeMetaTransaction.sol";
import {IMintableERC721} from "../../common/IMintableERC721.sol";
import {ContextMixin} from "../../common/ContextMixin.sol";
import {IParcelMinter} from "../IParcelMinter.sol";
import {ERC165Storage} from "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol";
import {Pausable } from "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
contract RootLand is
AccessControl,
NativeMetaTransaction,
IMintableERC721,
ERC721URIStorage,
Ownable,
ContextMixin,
IERC2981,
ERC165Storage,
Pausable
{
uint256 private startDate;
bytes32 public constant PREDICATE_ROLE = keccak256("PREDICATE_ROLE");
string public baseURI;
IParcelMinter public parcelMinter;
address public auctionAddress;
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
uint256 private _royaltyPercentage;
address private _royaltyAddress;
event LandPaused(address owner);
event LandUnpaused(address owner);
constructor(
string memory name_,
string memory symbol_,
string memory url_
) ERC721(name_, symbol_) {
_setupRole(DEFAULT_ADMIN_ROLE, _senderAddr());
_setupRole(PREDICATE_ROLE, _senderAddr());
_initializeEIP712(name_);
//implemented royalty based on this guidance https://eips.ethereum.org/EIPS/eip-2981
_registerInterface(_INTERFACE_ID_ERC2981);
baseURI = url_;
startDate = block.timestamp;
}
function setParcelMinter(address _minterAddress) external whenNotPaused onlyOwner {
parcelMinter = IParcelMinter(_minterAddress);
_setupRole(PREDICATE_ROLE, _minterAddress);
}
function setAuctionAddress(address _auctionAddress) external whenNotPaused onlyOwner {
auctionAddress = _auctionAddress;
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/**
* @dev See {IMintableERC721-mint}.
*/
function mint(address user, uint256 tokenId)
external
override
onlyRole(PREDICATE_ROLE)
whenNotPaused
{
_mint(user, tokenId);
}
/**
* If you're attempting to bring metadata associated with token
* from L2 to L1, you must implement this method, to be invoked
* when minting token back on L1, during exit
*/
function setTokenMetadata(uint256 tokenId, bytes memory data)
internal
virtual
{
// This function should decode metadata obtained from L2
// and attempt to set it for this `tokenId`
//
// Following is just a default implementation, feel
// free to define your own encoding/ decoding scheme
// for L2 -> L1 token metadata transfer
string memory uri = abi.decode(data, (string));
_setTokenURI(tokenId, uri);
}
/**
* @dev See {IMintableERC721-mint}.
*
* If you're attempting to bring metadata associated with token
* from L2 to L1, you must implement this method
*/
function mint(
address user,
uint256 tokenId,
bytes calldata metaData
) external override
onlyRole(PREDICATE_ROLE)
whenNotPaused
{
_mint(user, tokenId);
setTokenMetadata(tokenId, metaData);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, IERC165, ERC165Storage, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @dev See {IMintableERC721-exists}.
*/
function exists(uint256 tokenId) external view override returns (bool) {
return _exists(tokenId);
}
function _senderAddr() internal view returns (address payable sender) {
return ContextMixin.msgSender();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override
whenNotPaused
{
super._beforeTokenTransfer(from, to, tokenId);
if (from != auctionAddress && from != address(0))
{
require(block.timestamp > (startDate + 14 days), "NetVRKRootLand: Locked until January 25th");
}
}
/// @dev sets royalties info
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view override
whenNotPaused
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royaltyAddress;
royaltyAmount = (salePrice * _royaltyPercentage) / 100;
}
/// @dev sets royalties address
function setRoyaltyAddress(address royaltyAddress) public whenNotPaused onlyOwner {
_royaltyAddress = royaltyAddress;
}
/// @dev sets royalties fees
function setRoyaltyPercentage(uint256 royaltyPercentage) public whenNotPaused onlyOwner {
_royaltyPercentage = royaltyPercentage;
}
/// @dev pausing the contract
function pause() public onlyOwner
{
super._pause();
emit LandPaused(msgSender());
}
/// @dev unpause the contract
function unpause() public onlyOwner
{
super._unpause();
emit LandUnpaused(msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which 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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {EIP712Base} from "./EIP712Base.sol";
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH =
keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface IMintableERC721 is IERC721 {
/**
* @notice called by predicate contract to mint tokens while withdrawing
* @dev Should be callable only by MintableERC721Predicate
* Make sure minting is done only by this function
* @param user user address for whom token is being minted
* @param tokenId tokenId being minted
*/
function mint(address user, uint256 tokenId) external;
/**
* @notice called by predicate contract to mint tokens while withdrawing with metadata from L2
* @dev Should be callable only by MintableERC721Predicate
* Make sure minting is only done either by this function/ �
* @param user user address for whom token is being minted
* @param tokenId tokenId being minted
* @param metaData Associated token metadata, to be decoded & set using `setTokenMetadata`
*
* Note : If you're interested in taking token metadata from L2 to L1 during exit, you must
* implement this method
*/
function mint(
address user,
uint256 tokenId,
bytes calldata metaData
) external;
/**
* @notice check if token already exists, return true if it does exist
* @dev this check will be used by the predicate to determine if the token needs to be minted or transfered
* @param tokenId tokenId being checked
*/
function exists(uint256 tokenId) external view returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender() internal view returns (address payable sender) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
interface IParcelMinter {
function allocatedParcels(uint256 tokenId) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC165.sol";
/**
* @dev Storage based implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Storage is ERC165 {
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// 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 External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {Initializable} from "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string public constant ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contractsa that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(string memory name) internal initializer {
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
|
unpause the contract
|
function unpause() public onlyOwner
{
super._unpause();
emit LandUnpaused(msgSender());
}
| 5,474,160 |
pragma solidity ^0.4.18;
/**
* @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;
}
}
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;
}
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
pragma solidity ^0.4.19;
/// @title EtherHiLo
/// @dev the contract than handles the EtherHiLo app
contract EtherHiLo is usingOraclize, Ownable {
uint8 constant NUM_DICE_SIDES = 13;
// settings
uint public rngCallbackGas;
uint public minBet;
uint public maxBetThresholdPct;
bool public gameRunning;
// state
uint public balanceInPlay;
uint public totalGamesPlayed;
uint public totalBetsMade;
uint public totalWinnings;
mapping(address => Game) private gamesInProgress;
mapping(uint => address) private rollIdToGameAddress;
mapping(uint => uint) private failedRolls;
event GameStarted(address indexed player, uint indexed playerGameNumber, uint bet);
event FirstRoll(address indexed player, uint indexed playerGameNumber, uint bet, uint roll);
event DirectionChosen(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, BetDirection direction);
event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, uint finalRoll, uint winnings, uint payout);
event GameError(address indexed player, uint indexed playerGameNumber, uint rollId);
enum BetDirection {
None,
Low,
High
}
// the game object
struct Game {
address player;
BetDirection direction;
uint id;
uint bet;
uint firstRoll;
uint when;
}
// modifier that requires the game is running
modifier gameIsRunning() {
require(gameRunning);
_;
}
// modifier that requires there is a game in progress
// for the player
modifier gameInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player != address(0));
_;
}
// modifier that requires there is not a game in progress
// for the player
modifier gameNotInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player == address(0));
_;
}
// modifier that requires the caller come from oraclize
modifier onlyOraclize {
require(msg.sender == oraclize_cbAddress());
_;
}
// the constructor
function EtherHiLo() public {
oraclize_setProof(proofType_Ledger);
setRNGCallbackGas(1000000);
setRNGCallbackGasPrice(4000000000 wei);
setMinBet(1 finney);
setGameRunning(true);
setMaxBetThresholdPct(50);
totalGamesPlayed = 0;
totalBetsMade = 0;
totalWinnings = 0;
}
/// Default function
function() external payable {
}
/// =======================
/// EXTERNAL GAME RELATED FUNCTIONS
// begins a game
function beginGame() public payable
gameIsRunning
gameNotInProgress(msg.sender) {
address player = msg.sender;
uint bet = msg.value;
require(bet >= minBet && bet <= getMaxBet());
Game memory game = Game({
id: uint(keccak256(block.number, block.timestamp, player, bet)),
player: player,
bet: bet,
firstRoll: 0,
direction: BetDirection.None,
when: block.timestamp
});
balanceInPlay = balanceInPlay + game.bet;
totalGamesPlayed = totalGamesPlayed + 1;
totalBetsMade = totalBetsMade + game.bet;
gamesInProgress[player] = game;
if (rollDie(player, game.id)) {
GameStarted(player, game.id, bet);
}
}
// finishes a game that is in progress
function finishGame(BetDirection direction) public gameInProgress(msg.sender) {
address player = msg.sender;
require(player != address(0));
require(direction != BetDirection.None);
Game storage game = gamesInProgress[player];
require(game.player != address(0));
game.direction = direction;
gamesInProgress[player] = game;
if (rollDie(player, game.id)) {
DirectionChosen(player, game.id, game.bet, game.firstRoll, direction);
}
}
// determins whether or not the caller is in a game
function getGameState(address player) public view returns
(bool, uint, uint, BetDirection, uint, uint, uint) {
return (
gamesInProgress[player].player != address(0),
gamesInProgress[player].bet,
gamesInProgress[player].firstRoll,
gamesInProgress[player].direction,
gamesInProgress[player].id,
getMinBet(),
getMaxBet()
);
}
// Returns the minimum bet
function getMinBet() public view returns (uint) {
return minBet;
}
// Returns the maximum bet
function getMaxBet() public view returns (uint) {
return SafeMath.div(SafeMath.div(SafeMath.mul(this.balance - balanceInPlay, maxBetThresholdPct), 100), 12);
}
// calculates winnings for the given bet and percent
function calculateWinnings(uint bet, uint percent) public pure returns (uint) {
return SafeMath.div(SafeMath.mul(bet, percent), 100);
}
// Returns the win percent when going low on the given number
function getLowWinPercent(uint number) public pure returns (uint) {
require(number >= 2 && number <= NUM_DICE_SIDES);
if (number == 2) {
return 1200;
} else if (number == 3) {
return 500;
} else if (number == 4) {
return 300;
} else if (number == 5) {
return 300;
} else if (number == 6) {
return 200;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 150;
} else if (number == 9) {
return 140;
} else if (number == 10) {
return 130;
} else if (number == 11) {
return 120;
} else if (number == 12) {
return 110;
} else if (number == 13) {
return 100;
}
}
// Returns the win percent when going high on the given number
function getHighWinPercent(uint number) public pure returns (uint) {
require(number >= 1 && number < NUM_DICE_SIDES);
if (number == 1) {
return 100;
} else if (number == 2) {
return 110;
} else if (number == 3) {
return 120;
} else if (number == 4) {
return 130;
} else if (number == 5) {
return 140;
} else if (number == 6) {
return 150;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 200;
} else if (number == 9) {
return 300;
} else if (number == 10) {
return 300;
} else if (number == 11) {
return 500;
} else if (number == 12) {
return 1200;
}
}
/// =======================
/// INTERNAL GAME RELATED FUNCTIONS
// process a successful roll
function processDiceRoll(address player, uint roll) private {
Game storage game = gamesInProgress[player];
require(game.player != address(0));
if (game.firstRoll == 0) {
game.firstRoll = roll;
gamesInProgress[player] = game;
FirstRoll(player, game.id, game.bet, game.firstRoll);
return;
}
uint finalRoll = roll;
uint winnings = 0;
if (game.direction == BetDirection.High && finalRoll > game.firstRoll) {
winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll));
} else if (game.direction == BetDirection.Low && finalRoll < game.firstRoll) {
winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll));
}
// this should never happen according to the odds,
// and the fact that we don't allow people to bet
// so large that they can take the whole pot in one
// fell swoop - however, a number of people could
// theoretically all win simultaneously and cause
// this scenario. This will try to at a minimum
// send them back what they bet and then since it
// is recorded on the blockchain we can verify that
// the winnings sent don't match what they should be
// and we can manually send the rest to the player.
uint transferAmount = winnings;
if (transferAmount > this.balance) {
if (game.bet < this.balance) {
transferAmount = game.bet;
} else {
transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100);
}
}
balanceInPlay = balanceInPlay - game.bet;
if (transferAmount > 0) {
game.player.transfer(transferAmount);
}
totalWinnings = totalWinnings + winnings;
GameFinished(player, game.id, game.bet, game.firstRoll, finalRoll, winnings, transferAmount);
delete gamesInProgress[player];
}
// roll the dice for a player
function rollDie(address player, uint gameId) private returns (bool) {
uint N = 7;
uint delay = 0;
bytes32 _queryId = oraclize_newRandomDSQuery(delay, N, rngCallbackGas);
uint rollId = uint(keccak256(_queryId));
// avoid reorgs
if (failedRolls[rollId] == rollId) {
cleanupErrorGame(player, gameId, rollId);
return false;
}
rollIdToGameAddress[rollId] = player;
return true;
}
// called to cleanup an error in a game, usually caused by
// a reorg or other weird blockchain anomoly.
function cleanupErrorGame(address player, uint gameId, uint rollId) private {
Game storage game = gamesInProgress[player];
if (gameId == 0) {
gameId = game.id;
}
if (game.bet > 0) {
game.player.transfer(game.bet);
}
delete gamesInProgress[player];
delete rollIdToGameAddress[rollId];
delete failedRolls[rollId];
GameError(player, gameId, rollId);
}
/// =======================
/// ORACLIZE RELATED FUNCTIONS
// the callback function is called by Oraclize when the result is ready
// the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code:
// the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof) public onlyOraclize {
uint rollId = uint(keccak256(_queryId));
address player = rollIdToGameAddress[rollId];
// avoid reorgs
if (player == address(0)) {
failedRolls[rollId] = rollId;
return;
}
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
cleanupErrorGame(player, 0, rollId);
} else {
uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1;
processDiceRoll(player, randomNumber);
}
delete rollIdToGameAddress[rollId];
}
/// OWNER / MANAGEMENT RELATED FUNCTIONS
// fail safe for balance transfer
function transferBalance(address to, uint amount) public onlyOwner {
to.transfer(amount);
}
// cleans up a player abandoned game, but only if it's
// greater than 24 hours old.
function cleanupAbandonedGame(address player) public onlyOwner {
require(player != address(0));
Game storage game = gamesInProgress[player];
require(game.player != address(0));
uint elapsed = block.timestamp - game.when;
require(elapsed >= 86400);
game.player.transfer(game.bet);
delete gamesInProgress[game.player];
}
// set RNG callback gas
function setRNGCallbackGas(uint gas) public onlyOwner {
rngCallbackGas = gas;
}
// set RNG callback gas
function setRNGCallbackGasPrice(uint price) public onlyOwner {
oraclize_setCustomGasPrice(price);
}
// set the minimum bet
function setMinBet(uint bet) public onlyOwner {
minBet = bet;
}
// set whether or not the game is running
function setGameRunning(bool v) public onlyOwner {
gameRunning = v;
}
// set the max bet threshold percent
function setMaxBetThresholdPct(uint v) public onlyOwner {
maxBetThresholdPct = v;
}
// Transfers the current balance to the owner and terminates the contract.
function destroy() public onlyOwner {
selfdestruct(owner);
}
// Transfers the current balance to the recepient and terminates the contract.
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
}
|
roll the dice for a player avoid reorgs
|
function rollDie(address player, uint gameId) private returns (bool) {
uint N = 7;
uint delay = 0;
bytes32 _queryId = oraclize_newRandomDSQuery(delay, N, rngCallbackGas);
uint rollId = uint(keccak256(_queryId));
if (failedRolls[rollId] == rollId) {
cleanupErrorGame(player, gameId, rollId);
return false;
}
rollIdToGameAddress[rollId] = player;
return true;
}
| 2,073,420 |
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol
|
Reads the uint88 at `rdPtr` in returndata.
|
function readUint88(
ReturndataPointer rdPtr
) internal pure returns (uint88 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
| 4,300,429 |
./partial_match/1/0xf4671dc1b35dfd5a1eC5FAC2EAcC73B8E76Bb7D2/sources/MORT.sol
|
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);
}
}
| 9,189,691 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./IERC900.sol";
import "./RewardStreamer.sol";
import "./StakingLib.sol";
/// @title A Staking smart contract
/// @author Valerio Leo @valerioHQ
contract Staking is Initializable, IERC900, OwnableUpgradeable, RewardStreamer {
StakingLib.StakingInfo stakingInfo;
mapping(address => StakingLib.UserStake[]) private _userStakes;
/**
* Constructor
* @param _rewardToken The reward token address
* @param _ticket The raffle ticket address
* @param _locks The array with the locks durations values
* @param _rarityRegister The rarity register address
*/
function initialize (
address _rewardToken,
address _ticket,
uint256[] memory _locks,
uint256[] memory _locksMultiplier,
uint256 _ticketsMintingRatio,
uint256 _ticketsMintingChillPeriod,
address _rarityRegister,
address _defaultStaker
) public initializer {
require(_locks.length == _locksMultiplier.length, 'Stake: lock multiplier should have the same length ad locks');
OwnableUpgradeable.__Ownable_init();
super._setRewardToken(_rewardToken);
// add the default staker. we need a default staker to neveer have 0 staking units
_addStaker(_defaultStaker, 1 * 10**18, block.number + 1, 0);
stakingInfo.totalStakingUnits = stakingInfo.totalStakingUnits + (1 * 10 ** 18);
stakingInfo.totalCurrentlyStaked = stakingInfo.totalCurrentlyStaked + (1 * 10 ** 18);
stakingInfo.locks = _locks;
stakingInfo.locksMultiplier = _locksMultiplier;
stakingInfo.historyStartBlock = block.number;
stakingInfo.historyEndBlock = block.number;
setTicketsMintingChillPeriod(_ticketsMintingChillPeriod);
setTicketsMintingRatio(_ticketsMintingRatio);
setTicket(_ticket);
setRarityRegister(_rarityRegister);
RewardStreamer.rewardStreamInfo.deployedAtBlock = block.number;
}
/**
* @notice Will create a new reward stream
* @param rewardStreamIndex The reward index
* @param periodBlockRate The reward per block
* @param periodLastBlock The last block of the period
*/
function addRewardStream(uint256 rewardStreamIndex, uint256 periodBlockRate, uint256 periodLastBlock) public onlyOwner {
super._addRewardStream(rewardStreamIndex, periodBlockRate, periodLastBlock);
}
/**
* @notice Will add a new lock duration value
* @param lockNumber the new lock duration value
*/
function addLockDuration(uint256 lockNumber, uint256 lockMultiplier) public onlyOwner {
stakingInfo.locks.push(lockNumber);
stakingInfo.locksMultiplier.push(lockMultiplier);
emit LocksUpdated(stakingInfo.locks.length - 1, lockNumber, lockMultiplier);
}
event LocksUpdated(uint256 lockIndex, uint256 lockNumber, uint256 lockMultiplier);
/**
* @notice Will update an existing lock value
* @param lockIndex the lock index
* @param lockNumber the new lock duration value
*/
function updateLocks(uint256 lockIndex, uint256 lockNumber, uint256 lockMultiplier) public onlyOwner {
stakingInfo.locks[lockIndex] = lockNumber;
stakingInfo.locksMultiplier[lockIndex] = lockMultiplier;
emit LocksUpdated(lockIndex, lockNumber, lockMultiplier);
}
event TicketMintingChillPeriodUpdated(uint256 newValue);
/**
* @notice Will update the ticketsMintingChillPeriod
* @param newTicketsMintingChillPeriod the new value
*/
function setTicketsMintingChillPeriod(uint256 newTicketsMintingChillPeriod) public onlyOwner {
require(newTicketsMintingChillPeriod > 0, "Staking: ticketsMintingChillPeriod can't be zero");
stakingInfo.ticketsMintingChillPeriod = newTicketsMintingChillPeriod;
emit TicketMintingChillPeriodUpdated(newTicketsMintingChillPeriod);
}
event TicketMintingRatioUpdated(uint256 newValue);
/**
* @notice Will update the numebr of staking units needed to earn one ticket
* @param newTicketsMintingRatio the new value
*/
function setTicketsMintingRatio(uint256 newTicketsMintingRatio) public onlyOwner {
stakingInfo.ticketsMintingRatio = newTicketsMintingRatio;
emit TicketMintingRatioUpdated(newTicketsMintingRatio);
}
/**
* @notice Will update the ticket address
* @param ticketAddress the new value
*/
function setTicket(address ticketAddress) public onlyOwner {
stakingInfo.ticket = ticketAddress;
}
event RarityRegisterUpdated(address rarityRegister);
/**
* @notice Will update the rarityRegister address
* @param newRarityRegister the new value
*/
function setRarityRegister(address newRarityRegister) public onlyOwner {
stakingInfo.rarityRegister = newRarityRegister;
emit RarityRegisterUpdated(newRarityRegister);
}
/**
* @notice Will calculate the total reward generated from start till now
* @return (uint256) The the calculated reward
*/
function getTotalGeneratedReward() external view returns(uint256) {
return RewardStreamerLib.unsafeGetRewardsFromRange(rewardStreamInfo, stakingInfo.historyStartBlock, block.number);
}
function historyStartBlock() public view returns (uint256) {return stakingInfo.historyStartBlock;}
function historyEndBlock() public view returns (uint256) {return stakingInfo.historyEndBlock;}
function historyAverageReward() public view returns (uint256) {return stakingInfo.historyAverageReward;}
function historyRewardPot() public view returns (uint256) {return stakingInfo.historyRewardPot;}
function totalCurrentlyStaked() public view returns (uint256) {return stakingInfo.totalCurrentlyStaked;}
function totalStakingUnits() public view returns (uint256) {return stakingInfo.totalStakingUnits;}
function totalDistributedRewards() public view returns (uint256) {return stakingInfo.totalDistributedRewards;}
function ticketsMintingRatio() public view returns (uint256) {return stakingInfo.ticketsMintingRatio;}
function ticketsMintingChillPeriod() public view returns (uint256) {return stakingInfo.ticketsMintingChillPeriod;}
function rarityRegister() public view returns (address) {return stakingInfo.rarityRegister;}
function locks(uint256 i) public view returns (uint256) {return stakingInfo.locks[i];}
function locksMultiplier(uint256 i) public view returns (uint256) {return stakingInfo.locksMultiplier[i];}
function userStakes(address staker, uint256 i) public view returns (StakingLib.UserStake memory) {
StakingLib.UserStake memory s;
return _userStakes[staker].length > i
? _userStakes[staker][i]
: s;
}
function userStakedTokens(address staker, uint256 stakeIndex) public view returns (StakingLib.UserStakedToken memory) {
StakingLib.UserStakedToken memory s;
return _userStakes[staker].length > stakeIndex
? _userStakes[staker][stakeIndex].userStakedToken
: s;
}
/**
* @notice Will calculate the current period length
* @return (uint256) The current period length
*/
function getCurrentPeriodLength() public view returns(uint256) {
return StakingLib.getCurrentPeriodLength(stakingInfo);
}
/**
* @notice Will calculate the current period total reward
* @return (uint256) The current period total reward
*/
function getTotalRewardInCurrentPeriod() public view returns(uint256) {
return RewardStreamerLib.unsafeGetRewardsFromRange(rewardStreamInfo, stakingInfo.historyEndBlock, block.number);
}
/**
* @notice Will calculate the current period average reward
* @return (uint256) The current period average
*/
function getCurrentPeriodAverageReward() public view returns(uint256) {
return StakingLib.getCurrentPeriodAverageReward(
stakingInfo,
getTotalRewardInCurrentPeriod(),
false
);
}
/**
* @notice Will calculate the history length in blocks
* @return (uint256) The history length
*/
function getHistoryLength() public view returns (uint256){
return StakingLib.getHistoryLength(stakingInfo);
}
/**
* @notice Will get the pool share for a specific stake
* @param staker the address of the owner of the stake
* @param stakeIndex the index of the stake
* @return (uint256) The userPoolShare
*/
function getStakerPoolShare(address staker, uint256 stakeIndex) public view returns (uint256) {
return StakingLib.userPoolShare(
_userStakes[staker],
stakeIndex,
stakingInfo.totalStakingUnits
);
}
/**
* @notice Will get the reward of a stake for the current period
* @param staker the address of the owner of the stake
* @param stakeIndex the index of the stake
* @return (uint256) The reward for current period
*/
function getStakerRewardFromCurrent(address staker, uint256 stakeIndex) public view returns (uint256) {
return StakingLib.getStakerRewardFromCurrentPeriod(
rewardStreamInfo,
stakingInfo,
_userStakes[staker],
stakeIndex
);
}
/**
* @notice Will calculate and return for how many block the stake has in history
* @param staker the address of the owner of the stake
* @param stakeIndex the index of the stake
* @return (uint256) The number of blocks in history
*/
function getStakerTimeInHistory(address staker, uint256 stakeIndex) public view returns (uint256) {
return StakingLib.getStakerTimeInHistory(
stakingInfo,
_userStakes[staker],
stakeIndex
);
}
/**
* @notice Will calculate and return what the history length was a the moment the stake was created
* @param staker the address of the owner of the stake
* @param stakeIndex the index of the stake
* @return (uint256) The length of the history
*/
function getHistoryLengthBeforeStakerEntered(address staker, uint256 stakeIndex) public view returns (uint256) {
return StakingLib.getHistoryLengthBeforeStakerEntered(
stakingInfo,
_userStakes[staker],
stakeIndex
);
}
/**
* @notice Will calculate and return the history average for a stake
* @param staker the address of the owner of the stake
* @param stakeIndex the index of the stake
* @return (uint256) The calculated history average
*/
function getHistoryAverageForStake(address staker, uint256 stakeIndex) public view returns (uint256) {
return StakingLib.getHistoryAverageForStaker(
stakingInfo,
_userStakes[staker],
stakeIndex
);
}
/**
* @return (uint256) The number of all the stakes user has ever staked
*/
function getUserStakes(address staker) public view returns(uint256) {
return _userStakes[staker].length;
}
/**
* @notice Will calculate and return the total reward user has accumulated till now for a specific stake
* @param staker the address of the owner of the stake
* @param stakeIndex the index of the stake
* @return (uint256) The total rewards accumulated till now
*/
function getStakerReward(address staker, uint256 stakeIndex) public view returns (uint256) {
return StakingLib.getStakerReward(
rewardStreamInfo,
stakingInfo,
_userStakes[staker],
stakeIndex
);
}
/**
* @notice Will calculate the rewards that user will get from history
* @param staker the address of the staker you wish to get the rewards
* @param stakeIndex the index of the stake
* @return uint256 The amount of tokes user will get from history
*/
function getStakerRewardFromHistory(address staker, uint256 stakeIndex) public view returns (uint256) {
return StakingLib.getStakerRewardFromHistory(
stakingInfo,
_userStakes[staker],
stakeIndex
);
}
function getClaimableTickets(address staker, uint256 stakeIndex) public view returns (uint256) {
require(_userStakes[staker].length > stakeIndex, "Staking: stake does not exist");
return StakingLib.getClaimableTickets(
_userStakes[staker][stakeIndex]
);
}
function claimTickets(uint256 stakeIndex) public {
require(_userStakes[msg.sender].length > stakeIndex, "Staking: stake does not exist");
StakingLib.claimTickets(
stakingInfo.ticket,
_userStakes[msg.sender][stakeIndex],
msg.sender
);
}
/**
* @notice Creates a stake instance for the staker
* @notice MUST trigger Staked event
* @dev The NFT should be in the rarityRegister
* @dev For each stake you can have only one NFT staked
* @param stakerAddress the address of the owner of the stake
* @param amountStaked the number of tokens to be staked
* @param blockNumber the block number at which the stake is created
* @param lockDuration the duration for which the tokens will be locked
*/
function _addStaker(address stakerAddress, uint256 amountStaked, uint256 blockNumber, uint256 lockDuration) internal {
_userStakes[stakerAddress].push(StakingLib.UserStake({
amountStaked: amountStaked,
stakingUnits: amountStaked,
enteredAtBlock: blockNumber,
historyAverageRewardWhenEntered: stakingInfo.historyAverageReward,
ticketsMintingRatioWhenEntered: stakingInfo.ticketsMintingRatio,
ticketsMintingChillPeriodWhenEntered: stakingInfo.ticketsMintingChillPeriod,
lockedTill: blockNumber + lockDuration,
rewardCredit: 0,
ticketsMinted: 0,
userStakedToken: StakingLib.UserStakedToken({
tokenAddress: address(0),
tokenId: 0
})
})
);
emit Staked(stakerAddress, amountStaked, stakingInfo.totalCurrentlyStaked, abi.encodePacked(_userStakes[stakerAddress].length - 1));
}
/**
* @notice Allows user to stake tokens
* @notice Optionaly user can stake an NFT token for extra reward
* @dev Users wil be able to unstake only after the lock durationn has pased.
* @dev The lock duration in the data bytes is required, its the index of the locks array
* Should be the fist 32 bytes in the bytes array
* @param amount the inumber of tokens to be staked
* @param data the bytes containing extra information about the staking
* lock duration index: fist 32 bytes (Number) - Required
* NFT address: next 20 bytes (address)
* NFT tokenId: next 32 bytes (Number)
*/
function stake(uint256 amount, bytes calldata data) public override {
StakingLib.stake(
rewardStreamInfo,
stakingInfo,
_userStakes[msg.sender],
msg.sender,
amount,
data
);
emit Staked(
msg.sender,
amount,
stakingInfo.totalCurrentlyStaked,
abi.encodePacked(_userStakes[msg.sender].length - 1)
);
}
/**
* @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller
* @notice MUST trigger Staked event
* @param user the address the tokens are staked for
* @param amount uint256 the amount of tokens to stake
* @param data bytes aditional data for the stake and to include in the Stake event
* lock duration index: fist 32 bytes (Number) - Required
* NFT address: next 20 bytes (address)
* NFT tokenId: next 32 bytes (Number)
*/
function stakeFor(address user, uint256 amount, bytes calldata data) external override {
StakingLib.stake(
rewardStreamInfo,
stakingInfo,
_userStakes[user],
user,
amount,
data
);
emit Staked(user, amount, stakingInfo.totalCurrentlyStaked, abi.encodePacked(_userStakes[user].length - 1));
}
/**
* @notice Allows user to stake an nft to an existing stake for extra reward
* @dev The stake should exist
* @dev when adding the NFT we need to simulate an untake/stake because we need to recalculate the
* new historyAverageAmount, stakingInfo.totalStakingUnits and stakingInfo.historyRewardPot
* @notice it MUST revert if the added token has no multiplier
* @param staker the address of the owner of the stake
* @param stakeIndex the index of the stake
* @param tokenAddress the address of the NFT
* @param tokenId the id of the NFT token
*/
function addNftToStake(address staker, uint256 stakeIndex, address tokenAddress, uint256 tokenId) public {
StakingLib.addNftToStake(
rewardStreamInfo,
stakingInfo,
_userStakes[staker],
stakeIndex,
tokenAddress,
tokenId
);
}
/**
* @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert
* @notice MUST trigger Unstaked event
* @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens.
* @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be
* transferred back to their account, and their personalStakeIndex will increment to the next active stake.
* @param amount uint256 the amount of tokens to unstake
* @param data bytes optional data to include in the Unstake event
*/
function unstake(uint256 amount, bytes calldata data) public override {
uint256 stakerReward = StakingLib.unstake(
rewardStreamInfo,
stakingInfo,
_userStakes[msg.sender],
StakingLib.getStakeIndexFromCalldata(data)
);
emit Unstaked(
msg.sender,
stakerReward,
stakingInfo.totalCurrentlyStaked,
abi.encodePacked(StakingLib.getStakeIndexFromCalldata(data))
);
}
/**
* @notice This function offers a way to withdraw a ERC721 after using failsafeUnstakeERC20.
* @notice If for any reason the ERC721 should function again, this function allows to withdraw it.
* @param data bytes optional data to include in the Unstake event
*/
function unstakeERC721(bytes calldata data) external {
uint256 stakeIndex = StakingLib.getStakeIndexFromCalldata(data);
require(_userStakes[msg.sender][stakeIndex].lockedTill < block.number, "Staking: Stake is still locked");
StakingLib.removeNftFromStake(
_userStakes[msg.sender][stakeIndex].userStakedToken,
msg.sender
);
}
/**
* @notice Returns the current total of tokens staked for an address
* @param staker address The address to query
* @return uint256 The number of tokens staked for the given address
*/
function totalStakedFor(address staker) external override view returns (uint256) {
return StakingLib.getTotalStakedFor(_userStakes[staker]);
}
/**
* @notice Returns the current total of tokens staked
* @return uint256 The number of tokens staked in the contract
*/
function totalStaked() external override view returns (uint256) {
return stakingInfo.totalCurrentlyStaked;
}
/**
* @notice MUST return true if the optional history functions are implemented, otherwise false
* @dev Since we don't implement the optional interface, this always returns false
* @return bool Whether or not the optional history functions are implemented
*/
function supportsHistory() external override pure returns (bool) {
return false;
}
/**
* @notice Address of the token being used by the staking interface
* @return address The address of the ERC20 token used for staking
*/
function token() external override view returns (address) {
return address(rewardStreamInfo.rewardToken);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
/* solium-disable */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC900 Simple Staking Interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*/
interface IERC900 {
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
function stake(uint256 amount, bytes calldata data) external;
function stakeFor(address user, uint256 amount, bytes calldata data) external;
function unstake(uint256 amount, bytes calldata data) external;
function totalStakedFor(address addr) external view returns (uint256);
function totalStaked() external view returns (uint256);
function token() external view returns (address);
function supportsHistory() external pure returns (bool);
// NOTE: Not implementing the optional functions
// function lastStakedFor(address addr) public view returns (uint256);
// function totalStakedForAt(address addr, uint256 blockNumber) public view returns (uint256);
// function totalStakedAt(uint256 blockNumber) public view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./RewardStreamerLib.sol";
/// @title A Staking smart contract
/// @author Valerio Leo @valerioHQ
contract RewardStreamer {
RewardStreamerLib.RewardStreamInfo public rewardStreamInfo;
event RewardStreamAdded(uint256 rewardPerBlock, uint256 rewardLastBlock, uint256 rewardInStream);
function rewardToken() public view returns (address) {return address(rewardStreamInfo.rewardToken);}
/**
* @notice Will setup the token to use for reward
* @param rewardTokenAddress The reward token address
*/
function _setRewardToken(address rewardTokenAddress) internal {
RewardStreamerLib.setRewardToken(rewardStreamInfo, rewardTokenAddress);
}
/**
* @notice Will create a new reward stream
* @param rewardStreamIndex The reward index
* @param rewardPerBlock The amount of tokens rewarded per block
* @param rewardLastBlock The last block of the period
*/
function _addRewardStream(uint256 rewardStreamIndex, uint256 rewardPerBlock, uint256 rewardLastBlock) internal {
uint256 tokensInReward = RewardStreamerLib.addRewardStream(
rewardStreamInfo,
rewardStreamIndex,
rewardPerBlock,
rewardLastBlock
);
emit RewardStreamAdded(rewardPerBlock, rewardLastBlock, tokensInReward);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../NFTRarityRegister/INFTRarityRegister.sol";
import "../Raffle/IRaffleTicket.sol";
import "./RewardStreamerLib.sol";
import "./TokenHelper.sol";
library StakingLib {
// **************************
// **| StakingLib section |**
// **************************
struct StakingInfo {
uint256 historyStartBlock; // this is set only when we deploy the contract
uint256 historyEndBlock; // it starts and finishes in the same block (so length is 0)
uint256 historyAverageReward; // how many reward tokens (in Wei) we give PER TOKEN STAKED PER BLOCK
uint256 historyRewardPot; // the tokens unclaimed from history
uint256 totalCurrentlyStaked; // the actual amount of $BURP tokens sent from users
uint256 totalStakingUnits; // sum of all user stake shares
uint256 totalDistributedRewards; // sum of all distributed rewards, mainly helpful for testing
uint256[] locks;
uint256[] locksMultiplier;
uint256 ticketsMintingRatio;
uint256 ticketsMintingChillPeriod;
address ticket;
address rarityRegister;
}
/**
* @notice Will get the lock duration from the stake bytes data
* @dev the bytes should contain the index of the lock in the first 32 bytes
* @dev the index should be < locks.length
* @param data bytes from the stake action
* @return uint256 The duration of the lock (time for which the stake will be locked)
*/
function getLockDuration(StakingInfo storage stakingInfo, bytes memory data) public view returns (uint256, uint256) {
require(data.length >= 32, 'Stake: data should by at least 32 bytes');
uint256 lengthIndex = getStakeIndexFromCalldata(data);
require(lengthIndex < stakingInfo.locks.length, 'Stake: lock index out of bounds');
return (stakingInfo.locks[lengthIndex], lengthIndex);
}
/**
* @notice Will calculate the current period length
* @return (uint256) The current period length
*/
function getCurrentPeriodLength(StakingInfo storage stakingInfo) public view returns(uint256) {
return uint256(block.number) - stakingInfo.historyEndBlock;
}
/**
* @notice Will calculate the current period length optionally including the last block
* @param excludeLast a flag that indicates to include the last block or not
* @return (uint256) The current period length
*/
function getCurrentPeriodLength(StakingInfo storage stakingInfo, bool excludeLast) public view returns(uint256) {
return excludeLast ? getCurrentPeriodLength(stakingInfo) - 1 : getCurrentPeriodLength(stakingInfo);
}
/**
* @notice Will calculate the history length in blocks
* @return (uint256) The history length
*/
function getHistoryLength(StakingInfo storage stakingInfo) public view returns (uint256){
return stakingInfo.historyEndBlock - stakingInfo.historyStartBlock;
}
/**
* @notice Calculate the average reward for the current period
* @param stakingInfo the struct containing staking info
* @param totalReward the total reward in current period
* @param excludeLast whether or not exclude the last block
* @return (uint256) number of blocks in history
*/
function getCurrentPeriodAverageReward(
StakingInfo storage stakingInfo,
uint256 totalReward,
bool excludeLast
)
public
view
returns(uint256)
{
if (stakingInfo.totalStakingUnits == 0) {
return 0;
}
uint256 currentPeriodLength = getCurrentPeriodLength(stakingInfo, excludeLast);
if(currentPeriodLength == 0 ) {
return 0;
}
return totalReward
* (10**18)
/ (stakingInfo.totalStakingUnits)
/ (currentPeriodLength);
}
/**
* @notice Calculate the total generated reward for a period
* @param _block the current block
* @param historyStartBlock the first history block
* @param rewardPerBlock the amount of tokens rewarded per block
* @return (uint256) number of blocks in history
*/
function totalGeneratedReward(uint256 _block, uint256 historyStartBlock, uint256 rewardPerBlock) public pure returns(uint256) {
return (_block - historyStartBlock) * rewardPerBlock;
}
/**
* @notice Calculate the reward from current period
* @param totalRewardInCurrentPeriod the total reward from current period
* @param totalStakingUnits sum of all user stake shares
* @return (uint256) the calculated reward
*/
function _stakerRewardFromCurrentPeriod(
uint256 totalRewardInCurrentPeriod,
uint256 stakerBalance,
uint256 totalStakingUnits
)
private
pure
returns(uint256)
{
return totalRewardInCurrentPeriod
* stakerBalance
/ totalStakingUnits;
}
/**
* @notice Calculate the reward from current period
* @return (uint256) the calculated reward
*/
function getStakerRewardFromCurrentPeriod(
RewardStreamerLib.RewardStreamInfo storage rewardStreamInfo,
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
public
view
returns(uint256)
{
if (stakeIndex >= userStakes.length) {
return 0;
}
uint256 stakerBalance = userStakes[stakeIndex].stakingUnits;
uint256 totalRewardInCurrentPeriod = RewardStreamerLib.unsafeGetRewardsFromRange(
rewardStreamInfo,
stakingInfo.historyEndBlock,
block.number
);
return _stakerRewardFromCurrentPeriod(
totalRewardInCurrentPeriod,
stakerBalance,
stakingInfo.totalStakingUnits
);
}
/**
* @notice Calculate the reward from current period
* @return (uint256) the calculated reward
*/
function getStakerRewardFromCurrentPeriodAndUpdateCursor(
RewardStreamerLib.RewardStreamInfo storage rewardStreamInfo,
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
private
returns(uint256)
{
if (stakeIndex >= userStakes.length) {
return 0;
}
uint256 stakerBalance = userStakes[stakeIndex].stakingUnits;
uint256 totalRewardInCurrentPeriod = RewardStreamerLib.getRewardAndUpdateCursor(
rewardStreamInfo,
stakingInfo.historyEndBlock,
block.number - 1
);
return _stakerRewardFromCurrentPeriod(
totalRewardInCurrentPeriod,
stakerBalance,
stakingInfo.totalStakingUnits
);
}
/**
* @notice Will calculate and return the total reward user has accumulated till now for a specific stake
* @param stakeIndex the index of the stake
* @return (uint256) The total rewards accumulated till now
*/
function getStakerReward(
RewardStreamerLib.RewardStreamInfo storage rewardStreamInfo,
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
public
view
returns (uint256)
{
uint256 currentPeriodReward = getStakerRewardFromCurrentPeriod(rewardStreamInfo, stakingInfo, userStakes, stakeIndex);
uint256 historyPeriodReward = getStakerRewardFromHistory(stakingInfo, userStakes, stakeIndex);
return currentPeriodReward + historyPeriodReward;
}
/**
* @notice Will calculate and return the total reward user has accumulated till now for a specific stake
* @param stakeIndex the index of the stake
* @return (uint256) The total rewards accumulated till now
*/
function _getStakerReward(
RewardStreamerLib.RewardStreamInfo storage rewardStreamInfo,
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
private
returns (uint256)
{
uint256 currentPeriodReward = getStakerRewardFromCurrentPeriodAndUpdateCursor(rewardStreamInfo, stakingInfo, userStakes, stakeIndex);
uint256 historyPeriodReward = getStakerRewardFromHistory(stakingInfo, userStakes, stakeIndex);
return currentPeriodReward + historyPeriodReward;
}
/**
* @notice Creates a stake instance for the staker
* @notice MUST trigger Staked event
* @dev The NFT should be in the rarityRegister
* @dev For each stake you can have only one NFT staked
* @param amountStaked the number of tokens to be staked
* @param blockNumber the block number at which the stake is created
* @param lockDuration the duration for which the tokens will be locked
*/
function addStake(
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 amountStaked,
uint256 stakingUnits,
uint256 blockNumber,
uint256 lockDuration
)
private
{
userStakes.push(UserStake({
amountStaked: amountStaked,
stakingUnits: stakingUnits,
enteredAtBlock: blockNumber,
historyAverageRewardWhenEntered: stakingInfo.historyAverageReward,
ticketsMintingRatioWhenEntered: stakingInfo.ticketsMintingRatio,
ticketsMintingChillPeriodWhenEntered: stakingInfo.ticketsMintingChillPeriod,
lockedTill: blockNumber + lockDuration,
rewardCredit: 0,
ticketsMinted: 0,
userStakedToken: StakingLib.UserStakedToken({
tokenAddress: address(0),
tokenId: 0
})
})
);
}
/**
* @notice Allows user to stake tokens
* @notice Optionally user can stake a NFT token for extra reward
* @dev Users wil be able to unstake only after the lock durationn has pased.
* @dev The lock duration in the data bytes is required, its the index of the locks array
* Should be the fist 32 bytes in the bytes array
* @param amount the inumber of tokens to be staked
* @param data the bytes containing extra information about the staking
* lock duration index: fist 32 bytes (Number) - Required
* NFT address: next 20 bytes (address)
* NFT tokenId: next 32 bytes (Number)
*/
function stake(
RewardStreamerLib.RewardStreamInfo storage rewardStreamInfo,
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
address staker,
uint256 amount,
bytes calldata data
)
public
{
(uint256 lockDuration, uint256 lockIndex) = getLockDuration(stakingInfo, data);
TokenHelper.ERC20TransferFrom(address(rewardStreamInfo.rewardToken), msg.sender, address(this), amount);
updateHistoryValues(rewardStreamInfo, stakingInfo);
uint256 durationMultiplier = stakingInfo.locksMultiplier[lockIndex];
// when staking without any multiplier, staking units and amount are identical
stakingInfo.totalStakingUnits = stakingInfo.totalStakingUnits + applyPercent(amount, durationMultiplier);
stakingInfo.totalCurrentlyStaked = stakingInfo.totalCurrentlyStaked + amount;
addStake(stakingInfo, userStakes, amount, applyPercent(amount, durationMultiplier), block.number, lockDuration);
if (data.length >= 84) { // [32, 20. 32] == [index, address, tokenId]
addNftToStake(
rewardStreamInfo,
stakingInfo,
userStakes,
userStakes.length - 1,
getTokenAddressFromCalldata(data),
getTokenIdFromCalldata(data)
);
}
claimTickets(
stakingInfo.ticket,
userStakes[userStakes.length - 1], // last stake just created
staker
);
}
/**
* @notice Calculate the new history reward pot
* @param oldHistoryRewardPot the old history reward pot
* @param totalRewardInCurrentPeriod the total reward from current period
* @param stakerReward the staker reward
* @return (uint256) the new history reward pot
*/
function historyRewardPot(
uint256 oldHistoryRewardPot,
uint256 totalRewardInCurrentPeriod,
uint256 stakerReward
) public pure returns(uint256) {
return oldHistoryRewardPot
+ totalRewardInCurrentPeriod
- stakerReward;
}
/**
* @notice Will parse bytes data to get an uint256
* @param data bytes data
* @param from from where to start the parsing
*/
function parse32BytesToUint256(bytes memory data, uint256 from) public pure returns (uint256 parsed){
assembly {parsed := mload(add(add(data, from), 32))}
}
/**
* @notice Will parse bytes data to get an address
* @param data bytes data
* @param from from where to start the parsing
*/
function parseBytesToAddress(bytes memory data, uint256 from) public pure returns (address parsed){
assembly {parsed := mload(add(add(data, from), 20))}
}
/**
* @notice Will parse the stake bytes data to get the stake index
* @dev [(index 32 bytes), (nft address 20 bytes), (tokenId 32 bytes)]
* @param data bytes from the stake action
* @return (uint256) the parsed index
*/
function getStakeIndexFromCalldata(bytes memory data) public pure returns (uint256) {
return parse32BytesToUint256(data, 0);
}
/**
* @notice Will parse the stake bytes data to get the NFT address
* @dev [(index 32 bytes), (nft address 20 bytes), (tokenId 32 bytes)]
* @param data bytes from the stake action
* @return (address) the parsed address
*/
function getTokenAddressFromCalldata(bytes memory data) public pure returns (address) {
return parseBytesToAddress(data, 32);
}
/**
* @notice Will parse the stake bytes data to get the NFT tokeId
* @dev [(index 32 bytes), (nft address 20 bytes), (tokenId 32 bytes)]
* @param data bytes from the stake action
* @return (uint256) the parsed tokenId
*/
function getTokenIdFromCalldata(bytes memory data) public pure returns (uint256) {
return parse32BytesToUint256(data, 52);
}
/**
* @notice Will apply a percentage to a number
* @param number The number to multiply
* @param percent The percentage to apply
* @return (uint256) the operation result
*/
function applyPercent(uint256 number, uint256 percent) public pure returns (uint256) {
return number * percent / 100;
}
/**
* @notice Calculates the new History Average Reward
* @dev this is called **before** we update history end block
* @return uint256 The calculated newHistoryAverageReward
*/
function getNewHistoryAverageReward(
uint256 currentPeriodLength,
uint256 currentPeriodAverageReward,
uint256 currentHistoryLength,
uint256 historyStartBlock,
uint256 historyAverageReward
) public view returns (uint256) {
uint256 blockNumber = block.number;
uint256 newHistoryLength = uint256(blockNumber)- 1 - historyStartBlock;
uint256 fromCurrent = currentPeriodLength * currentPeriodAverageReward;
uint256 fromHistory = currentHistoryLength * historyAverageReward;
uint256 newHistoryAverageReward = (
fromCurrent + fromHistory
)
/ newHistoryLength;
return newHistoryAverageReward;
}
function updateHistoryValues(
RewardStreamerLib.RewardStreamInfo storage rewardStreamInfo,
StakingInfo storage stakingInfo
)
public
{
uint256 totalRewardInCurrentPeriod = RewardStreamerLib.getRewardAndUpdateCursor(
rewardStreamInfo,
stakingInfo.historyEndBlock,
block.number - 1
);
uint256 currentPeriodAverageReward = getCurrentPeriodAverageReward(
stakingInfo,
totalRewardInCurrentPeriod,
true
);
// 1. we update the stakingInfo.historyAverageReward with the WEIGHTED average of history reward and current reward
stakingInfo.historyAverageReward = getNewHistoryAverageReward(
getCurrentPeriodLength(stakingInfo, true),
currentPeriodAverageReward,
getHistoryLength(stakingInfo),
stakingInfo.historyStartBlock,
stakingInfo.historyAverageReward
);
// 2. we push the currentPeriodReward in the history
stakingInfo.historyRewardPot = historyRewardPot(
stakingInfo.historyRewardPot,
totalRewardInCurrentPeriod,
0
);
// 3. we update the stakingInfo.historyEndBlock;
stakingInfo.historyEndBlock = uint256(block.number) - 1;
}
function setTicketsMintingRatio(
StakingInfo storage stakingInfo,
uint256 mintingRatio
)
public
{
stakingInfo.ticketsMintingRatio = mintingRatio;
}
// *****************************
// *** UserStakesLib section ***
// *****************************
struct UserStakedToken {
address tokenAddress;
uint256 tokenId;
}
struct UserStake {
uint256 stakingUnits;
uint256 amountStaked;
uint256 enteredAtBlock;
uint256 historyAverageRewardWhenEntered;
uint256 ticketsMintingRatioWhenEntered;
uint256 ticketsMintingChillPeriodWhenEntered;
uint256 lockedTill;
uint256 rewardCredit;
uint256 ticketsMinted;
UserStakedToken userStakedToken;
}
function getTotalStakedFor(
UserStake[] storage userStakes
)
public
view
returns (uint256)
{
uint256 total;
for (uint i = 0; i < userStakes.length; i++) {
total = total + userStakes[i].amountStaked;
}
return total;
}
/**
* @notice Calculate the staker time in history
* @return (uint256) number of blocks in history
*/
function getStakerTimeInHistory(
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
public
view
returns(uint256)
{
if (stakeIndex >= userStakes.length || userStakes[stakeIndex].enteredAtBlock == 0 || userStakes[stakeIndex].enteredAtBlock > stakingInfo.historyEndBlock) {
return 0;
}
return stakingInfo.historyEndBlock - userStakes[stakeIndex].enteredAtBlock + 1;
}
/**
* @notice Will calculate and return what the history length was a the moment the stake was created
* @param stakeIndex the index of the stake
* @return (uint256) The length of the history
*/
function getHistoryLengthBeforeStakerEntered(
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
public
view
returns (uint256)
{
uint256 enteredAtBlock = userStakes[stakeIndex].enteredAtBlock;
if (enteredAtBlock == 0) {
return 0;
}
return enteredAtBlock - stakingInfo.historyStartBlock - 1;
}
/**
* @notice Calculate the user share in the pool
* @param totalStakingUnits sum of all user stake shares
* @return (uint256) the calculated pool share
*/
function userPoolShare(
UserStake[] storage userStakes,
uint256 stakeIndex,
uint256 totalStakingUnits
)
public
view
returns(uint256)
{
if (stakeIndex >= userStakes.length || userStakes[stakeIndex].stakingUnits == 0) {
return 0;
}
uint256 stakerBalance = userStakes[stakeIndex].stakingUnits;
return stakerBalance * (10**18) / totalStakingUnits;
}
/**
* @notice Calculate the history average for staker
* @return (uint256) the calculated average
*/
function getHistoryAverageForStaker(
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
public
view
returns(uint256)
{
if (stakeIndex >= userStakes.length) {
return 0;
}
uint256 historyAverageRewardWhenEntered = userStakes[stakeIndex].historyAverageRewardWhenEntered;
uint256 blocksParticipatedInHistory = getStakerTimeInHistory(
stakingInfo,
userStakes,
stakeIndex
);
if(blocksParticipatedInHistory == 0) {
return 0;
}
uint256 historyLength = getHistoryLength(stakingInfo);
uint256 historyLengthBeforeStakerEntered = getHistoryLengthBeforeStakerEntered(
stakingInfo,
userStakes,
stakeIndex
);
return (stakingInfo.historyAverageReward * historyLength - historyAverageRewardWhenEntered * historyLengthBeforeStakerEntered) / blocksParticipatedInHistory;
}
/**
* @notice Calculate the stake reward from history
* @return (uint256) the calculated reward
*/
function getStakerRewardFromHistory(
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
public
view
returns(uint256)
{
if (stakeIndex >= userStakes.length) {
return 0;
}
uint256 stakingUnits = userStakes[stakeIndex].stakingUnits;
if (stakingUnits == 0) {
return 0;
}
uint256 historyAverageForStaker = getHistoryAverageForStaker(
stakingInfo,
userStakes,
stakeIndex
);
uint256 blocksParticipatedInHistory = getStakerTimeInHistory(
stakingInfo,
userStakes,
stakeIndex
);
return blocksParticipatedInHistory
* historyAverageForStaker
* stakingUnits
/ (10 ** 18);
}
/**
* @notice Allows user to stake an nft to an existing stake for extra reward
* @dev The NFT should be in the rarityRegister
* @dev For each stake you can have only one NFT staked
*/
function _addNftToStakeAndApplyMultiplier(
address rarityRegister,
UserStake storage userStake,
address tokenAddress,
uint256 tokenId
)
private
{
uint256 rewardMultiplier = INFTRarityRegister(rarityRegister).getNftRarity(tokenAddress, tokenId);
require(rewardMultiplier > 0, 'Staking: NFT not found in RarityRegister');
require(rewardMultiplier >= 100, 'Staking: NFT multiplier must be at least 100');
require(
userStake.userStakedToken.tokenAddress == address(0),
'Staking: Stake already has a token'
);
require(
userStake.lockedTill > block.number,
'Staking: cannot add NFT to unlocked stakes'
);
uint userStakingUnits = userStake.stakingUnits;
bool success = TokenHelper.transferFrom(tokenAddress, tokenId, msg.sender, address(this));
require(success, "Staking: could not add NFT to stake");
userStake.userStakedToken.tokenAddress = tokenAddress;
userStake.userStakedToken.tokenId = tokenId;
userStake.stakingUnits = applyPercent(userStakingUnits, rewardMultiplier);
}
/**
* @notice Allows user to stake an nft to an existing stake for extra reward
* @dev The stake should exist
* @dev when adding the NFT we need to simulate an unstake/stake because we need to recalculate the
* new historyAverageAmount, stakingInfo.totalStakingUnits and stakingInfo.historyRewardPot
* @notice it MUST revert if the added token has no multiplier
*/
function addNftToStake(
RewardStreamerLib.RewardStreamInfo storage rewardStreamInfo,
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex,
address tokenAddress,
uint256 tokenId
)
public
{
uint256 previousStakingUnits = userStakes[stakeIndex].stakingUnits; // this stays the same
require(previousStakingUnits > 0, "Staking: Stake not found");
uint256 stakerReward = _getStakerReward(
rewardStreamInfo,
stakingInfo,
userStakes,
stakeIndex
);
_addNftToStakeAndApplyMultiplier(
stakingInfo.rarityRegister,
userStakes[stakeIndex],
tokenAddress,
tokenId
);
uint256 newStakingUnits = userStakes[stakeIndex].stakingUnits; // after we just update it
updateHistoryValues(rewardStreamInfo, stakingInfo);
// we bring the stake to the current time
userStakes[stakeIndex].enteredAtBlock = block.number;
userStakes[stakeIndex].historyAverageRewardWhenEntered = stakingInfo.historyAverageReward;
userStakes[stakeIndex].rewardCredit = stakerReward;
stakingInfo.totalStakingUnits = stakingInfo.totalStakingUnits
- previousStakingUnits
+ newStakingUnits;
stakingInfo.historyRewardPot = stakingInfo.historyRewardPot - stakerReward;
}
function _resetStake(UserStake storage userStake) private {
userStake.stakingUnits = 0;
userStake.rewardCredit = 0;
userStake.amountStaked = 0;
userStake.enteredAtBlock = 0;
userStake.lockedTill = 0;
userStake.ticketsMintingRatioWhenEntered = 0;
userStake.historyAverageRewardWhenEntered = 0;
userStake.ticketsMintingChillPeriodWhenEntered = 0;
}
/**
* @notice Remove the previously staked NFT from the stake
* @param staker the address of the owner of the stake
*/
function removeNftFromStake(
UserStakedToken storage userStakedToken,
address staker
)
public
{
if (userStakedToken.tokenAddress != address(0)) {
uint256 tokenId = userStakedToken.tokenId;
address tokenAddress = userStakedToken.tokenAddress;
bool success = TokenHelper.transferFrom(tokenAddress, tokenId, address(this), staker);
if(success) {
delete userStakedToken.tokenId;
delete userStakedToken.tokenAddress;
}
}
}
/**
* @notice Allows user to unstake the staked tokens
* @notice The tokens are allowed to be unstaked only after the lock duration has passed
* @notice MUST trigger Unstaked event
* @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens.
* @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be
* transferred back to their account, and their personalStakeIndex will increment to the next active stake.
* @return uint256 The number of tokens unstaked
*/
function unstake(
RewardStreamerLib.RewardStreamInfo storage rewardStreamInfo,
StakingInfo storage stakingInfo,
UserStake[] storage userStakes,
uint256 stakeIndex
)
public
returns (uint256)
{
require(stakeIndex < userStakes.length, 'Staking: Nothing to unstake');
require(userStakes[stakeIndex].lockedTill < block.number, "Staking: Stake is still locked");
require(userStakes[stakeIndex].amountStaked != 0, 'Staking: Nothing to unstake');
uint256 stakerReward = _getStakerReward(
rewardStreamInfo,
stakingInfo,
userStakes,
stakeIndex
);
// if for any reason the transfer fails, it will fail silently
// and token can be withdrawn when error disappears
removeNftFromStake(userStakes[stakeIndex].userStakedToken, msg.sender);
uint256 totalAmount = stakerReward
+ userStakes[stakeIndex].amountStaked
+ userStakes[stakeIndex].rewardCredit;
TokenHelper.ERC20Transfer(rewardStreamInfo.rewardToken, address(msg.sender), totalAmount);
updateHistoryValues(rewardStreamInfo, stakingInfo);
stakingInfo.totalDistributedRewards = stakingInfo.totalDistributedRewards + stakerReward + userStakes[stakeIndex].rewardCredit;
stakingInfo.totalCurrentlyStaked = stakingInfo.totalCurrentlyStaked - userStakes[stakeIndex].amountStaked;
stakingInfo.totalStakingUnits = stakingInfo.totalStakingUnits - userStakes[stakeIndex].stakingUnits;
claimTickets(stakingInfo.ticket, userStakes[stakeIndex], msg.sender);
_resetStake(userStakes[stakeIndex]);
stakingInfo.historyRewardPot = stakingInfo.historyRewardPot - stakerReward;
return stakerReward;
}
function getClaimableTickets(
UserStake storage userStake
)
public
view
returns (uint256)
{
uint256 stakingUnits = userStake.stakingUnits;
uint256 ticketsMintingChillPeriod = userStake.ticketsMintingChillPeriodWhenEntered;
uint256 ticketsMintingRatio = userStake.ticketsMintingRatioWhenEntered;
uint256 ticketsMinted = userStake.ticketsMinted;
if(stakingUnits == 0 || ticketsMintingRatio == 0 || ticketsMintingChillPeriod == 0) {
return 0;
}
// 2. get chilling period length
// 3. check how many periods have passed
uint256 enteredAtBlock = userStake.enteredAtBlock;
uint256 lockedTill = userStake.lockedTill;
// 4. prevent minting more tickets after stake is unlocked
uint256 blocksDelta = Math.min(
(uint256(block.number) - enteredAtBlock),
(lockedTill - enteredAtBlock)
) + ticketsMintingChillPeriod; // count as passed from day 0
uint256 periodsPassed = blocksDelta / ticketsMintingChillPeriod;
// 4. multiply tickets
uint256 multipliedUnits = stakingUnits * periodsPassed;
// 5. get printable tickets
uint256 printableTickets = multipliedUnits / ticketsMintingRatio;
// 6. subtract any previously minted
uint256 netPrintableTickets = printableTickets - ticketsMinted;
// 5. don't print more tickets after stake is unlocked
return netPrintableTickets;
}
/**
* @notice Mint tickets to the staker
* @notice The amount of tickets depends on the amount of tokens staked and the duration the tokens a locked for.
* @param ticket the address of the ticket instance
* @param userStake the stake to claim tickets from
* @param staker the address fo the staker
*/
function claimTickets(
address ticket,
UserStake storage userStake,
address staker
)
public
{
uint256 netPrintableTickets = getClaimableTickets(userStake);
if(netPrintableTickets > 0) {
TokenHelper._mintTickets(ticket, staker, netPrintableTickets);
userStake.ticketsMinted = userStake.ticketsMinted + netPrintableTickets;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./TokenHelper.sol";
library RewardStreamerLib {
struct RewardStreamInfo {
RewardStream[] rewardStreams;
uint256 deployedAtBlock;
address rewardToken;
}
struct RewardStream {
uint256[] periodRewards;
uint256[] periodEnds;
uint256 rewardStreamCursor;
}
/**
* @notice Will setup the token to use for reward
* @param rewardTokenAddress The reward token address
*/
function setRewardToken(RewardStreamInfo storage rewardStreamInfo, address rewardTokenAddress) public {
rewardStreamInfo.rewardToken = address(rewardTokenAddress);
}
/**
* @notice Will create a new reward stream
* @param rewardStreamIndex The reward index
* @param rewardPerBlock The amount of tokens rewarded per block
* @param rewardLastBlock The last block of the period
*/
function addRewardStream(
RewardStreamInfo storage rewardStreamInfo,
uint256 rewardStreamIndex,
uint256 rewardPerBlock,
uint256 rewardLastBlock
)
public
returns (uint256)
{
// e.g. current length = 0
require(rewardStreamIndex <= rewardStreamInfo.rewardStreams.length, "RewardStreamer: you cannot skip an index");
uint256 tokensInReward;
if(rewardStreamInfo.rewardStreams.length > rewardStreamIndex) {
RewardStream storage rewardStream = rewardStreamInfo.rewardStreams[rewardStreamIndex];
uint256[] storage periodEnds = rewardStream.periodEnds;
uint periodStart = periodEnds.length == 0
? rewardStreamInfo.deployedAtBlock
: periodEnds[periodEnds.length - 1];
require(periodStart < rewardLastBlock, "RewardStreamer: periodStart must be smaller than rewardLastBlock");
rewardStreamInfo.rewardStreams[rewardStreamIndex].periodEnds.push(rewardLastBlock);
rewardStreamInfo.rewardStreams[rewardStreamIndex].periodRewards.push(rewardPerBlock);
tokensInReward = (rewardLastBlock - periodStart) * rewardPerBlock;
} else {
RewardStream memory rewardStream;
uint periodStart = rewardStreamInfo.deployedAtBlock;
require(periodStart < rewardLastBlock, "RewardStreamer: periodStart must be smaller than rewardLastBlock");
rewardStreamInfo.rewardStreams.push(rewardStream);
rewardStreamInfo.rewardStreams[rewardStreamIndex].periodEnds.push(rewardLastBlock);
rewardStreamInfo.rewardStreams[rewardStreamIndex].periodRewards.push(rewardPerBlock);
tokensInReward = (rewardLastBlock - periodStart) * rewardPerBlock;
}
TokenHelper.ERC20TransferFrom(address(rewardStreamInfo.rewardToken), msg.sender, address(this), tokensInReward);
return tokensInReward;
}
/**
* @notice Get the rewards for a period
* @param fromBlock the block number from which the reward is calculated
* @param toBlock the block number till which the reward is calculated
* @return (uint256) the total reward
*/
function unsafeGetRewardsFromRange(
RewardStreamInfo storage rewardStreamInfo,
uint fromBlock,
uint toBlock
)
public
view
returns (uint256)
{
require(tx.origin == msg.sender, "StakingReward: unsafe function for contract call");
uint256 currentReward;
for(uint256 i; i < rewardStreamInfo.rewardStreams.length; i++) {
currentReward = currentReward + iterateRewards(
rewardStreamInfo,
i,
Math.max(fromBlock, rewardStreamInfo.deployedAtBlock),
toBlock,
0
);
}
return currentReward;
}
/**
* @notice Iterate the rewards
* @param rewardStreamIndex the index of the reward stream
* @param fromBlock the block number from which the reward is calculated
* @param toBlock the block number till which the reward is calculated
* @param rewardIndex the reward index
* @return (uint256) the calculate reward
*/
function iterateRewards(
RewardStreamInfo storage rewardStreamInfo,
uint256 rewardStreamIndex,
uint fromBlock,
uint toBlock,
uint256 rewardIndex
)
public
view
returns (uint256)
{
// the start block is bigger than
if(rewardIndex >= rewardStreamInfo.rewardStreams[rewardStreamIndex].periodRewards.length) {
return 0;
}
uint currentPeriodEnd = rewardStreamInfo.rewardStreams[rewardStreamIndex].periodEnds[rewardIndex];
uint currentPeriodReward = rewardStreamInfo.rewardStreams[rewardStreamIndex].periodRewards[rewardIndex];
uint256 totalReward = 0;
// what's the lowest block in current period?
uint currentPeriodStart = rewardIndex == 0
? rewardStreamInfo.deployedAtBlock
: rewardStreamInfo.rewardStreams[rewardStreamIndex].periodEnds[rewardIndex - 1];
// is the fromBlock included in period?
if(fromBlock <= currentPeriodEnd) {
uint256 lower = Math.max(fromBlock, currentPeriodStart);
uint256 upper = Math.min(toBlock, currentPeriodEnd);
uint256 blocksInPeriod = upper - lower;
totalReward = blocksInPeriod * currentPeriodReward;
} else {
return iterateRewards(
rewardStreamInfo,
rewardStreamIndex,
fromBlock,
toBlock,
rewardIndex + 1
);
}
if(toBlock > currentPeriodEnd) {
// we need to move to next reward period
totalReward += iterateRewards(
rewardStreamInfo,
rewardStreamIndex,
fromBlock,
toBlock,
rewardIndex + 1
);
}
return totalReward;
}
/**
* @notice Iterate the rewards and updates the cursor
* @notice NOTE: once the cursor is updated, the next call will start from the cursor
* @notice making it impossible to calculate twice the reward in a period
* @param rewardStreamInfo the struct holding current reward info
* @param fromBlock the block number from which the reward is calculated
* @param toBlock the block number till which the reward is calculated
* @return (uint256) the calculated reward
*/
function getRewardAndUpdateCursor (
RewardStreamInfo storage rewardStreamInfo,
uint256 fromBlock,
uint256 toBlock
)
public
returns (uint256)
{
uint256 currentReward;
for(uint256 i; i < rewardStreamInfo.rewardStreams.length; i++) {
currentReward = currentReward + iterateRewardsWithCursor(
rewardStreamInfo,
i,
Math.max(fromBlock, rewardStreamInfo.deployedAtBlock),
toBlock,
rewardStreamInfo.rewardStreams[i].rewardStreamCursor
);
}
return currentReward;
}
function bumpStreamCursor(
RewardStreamInfo storage rewardStreamInfo,
uint256 rewardStreamIndex
)
public
{
// this step is important to avoid going out of index
if(rewardStreamInfo.rewardStreams[rewardStreamIndex].rewardStreamCursor < rewardStreamInfo.rewardStreams[rewardStreamIndex].periodRewards.length) {
rewardStreamInfo.rewardStreams[rewardStreamIndex].rewardStreamCursor = rewardStreamInfo.rewardStreams[rewardStreamIndex].rewardStreamCursor + 1;
}
}
function iterateRewardsWithCursor(
RewardStreamInfo storage rewardStreamInfo,
uint256 rewardStreamIndex,
uint fromBlock,
uint toBlock,
uint256 rewardPeriodIndex
)
public
returns (uint256)
{
if(rewardPeriodIndex >= rewardStreamInfo.rewardStreams[rewardStreamIndex].periodRewards.length) {
return 0;
}
uint currentPeriodEnd = rewardStreamInfo.rewardStreams[rewardStreamIndex].periodEnds[rewardPeriodIndex];
uint currentPeriodReward = rewardStreamInfo.rewardStreams[rewardStreamIndex].periodRewards[rewardPeriodIndex];
uint256 totalReward = 0;
// what's the lowest block in current period?
uint currentPeriodStart = rewardPeriodIndex == 0
? rewardStreamInfo.deployedAtBlock
: rewardStreamInfo.rewardStreams[rewardStreamIndex].periodEnds[rewardPeriodIndex - 1];
// is the fromBlock included in period?
if(fromBlock <= currentPeriodEnd) {
uint256 lower = Math.max(fromBlock, currentPeriodStart);
uint256 upper = Math.min(toBlock, currentPeriodEnd);
uint256 blocksInPeriod = upper - lower;
totalReward = blocksInPeriod * currentPeriodReward;
} else {
// the fromBlock passed this reward period, we can start
// skipping it for next reads
bumpStreamCursor(rewardStreamInfo, rewardStreamIndex);
return iterateRewards(rewardStreamInfo, rewardStreamIndex, fromBlock, toBlock, rewardPeriodIndex + 1);
}
if(toBlock > currentPeriodEnd) {
// we need to move to next reward period
totalReward += iterateRewards(rewardStreamInfo, rewardStreamIndex, fromBlock, toBlock, rewardPeriodIndex + 1);
}
return totalReward;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute.
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import "../Raffle/IRaffleTicket.sol";
library TokenHelper {
function ERC20Transfer(
address token,
address to,
uint256 amount
)
public
{
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERC20: transfer amount exceeds balance');
}
function ERC20TransferFrom(
address token,
address from,
address to,
uint256 amount
)
public
{
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERC20: transfer amount exceeds balance or allowance');
}
function transferFrom(
address token,
uint256 tokenId,
address from,
address to
)
public
returns (bool)
{
(bool success,) = token.call(abi.encodeWithSelector(IERC721.transferFrom.selector, from, to, tokenId));
// in the ERC721 the transfer doesn't return a bool. So we need to check explicitly.
return success;
}
function _mintTickets(
address ticket,
address to,
uint256 amount
) public {
(bool success,) = ticket.call(abi.encodeWithSelector(IRaffleTicket.mint.selector, to, 0, amount));
require(success, 'ERC1155: mint failed');
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
/// @title A mintable NFT ticket for Coinburp Raffle
/// @author Valerio Leo @valerioHQ
interface IRaffleTicket is IERC1155 {
function mint(address to, uint256 tokenId, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Registry holding the rarity value of a given NFT.
/// @author Nemitari Ajienka @najienka
interface INFTRarityRegister {
/**
* The Staking SC allows to stake Prizes won via lottery which can be used to increase the APY of
* staked tokens according to the rarity of NFT staked. For this reason,
* we need to hold a table that the Staking SC can query and get back the rarity value of a given
* NFT price (even the ones in the past).
*/
event NftRarityStored(
address indexed tokenAddress,
uint256 tokenId,
uint256 rarityValue
);
/**
* @dev Store the rarity of a given NFT
* @param tokenAddress The NFT smart contract address e.g., ERC-721 standard contract
* @param tokenId The NFT's unique token id
* @param rarityValue The rarity of a given NFT address and id unique combination
*/
function storeNftRarity(address tokenAddress, uint256 tokenId, uint8 rarityValue) external;
/**
* @dev Get the rarity of a given NFT
* @param tokenAddress The NFT smart contract address e.g., ERC-721 standard contract
* @param tokenId The NFT's unique token id
* @return The the rarity of a given NFT address and id unique combination and timestamp
*/
function getNftRarity(address tokenAddress, uint256 tokenId) external view returns (uint8);
}
|
Will parse the stake bytes data to get the stake index [(index 32 bytes), (nft address 20 bytes), (tokenId 32 bytes)] data bytes from the stake action return (uint256) the parsed index/
|
function getStakeIndexFromCalldata(bytes memory data) public pure returns (uint256) {
return parse32BytesToUint256(data, 0);
}
| 497,256 |
/**
*Submitted for verification at Etherscan.io on 2021-12-27
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity >=0.6.4;
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.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, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}.
*/
contract BEP20 is Context, IBEP20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the name of the token.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-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 override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* 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 override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-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 {BEP20-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, 'BEP20: decreased allowance below zero'));
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
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), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'BEP20: 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), 'BEP20: 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), 'BEP20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'BEP20: 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), 'BEP20: approve from the zero address');
require(spender != address(0), 'BEP20: 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, 'BEP20: burn amount exceeds allowance'));
}
}
// OboToken with Governance.
contract OboToken is BEP20('OboSwap Token', 'OBO') {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
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;
/// @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 Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Obo::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Obo::delegateBySig: invalid nonce");
require(now <= expiry, "Obo::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 (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, "Obo::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 = balanceOf(delegator); // balance of underlying Obos (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, "Obo::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeBEP20
* @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeBEP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IBEP20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IBEP20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IBEP20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IBEP20 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),
"SafeBEP20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IBEP20 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(IBEP20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeBEP20: 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(IBEP20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeBEP20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeBEP20: BEP20 operation did not succeed");
}
}
}
// MasterChef is the master of Obo. He can make Obo and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once Obo is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of Obos
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accOboPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accOboPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. Obos to distribute per block.
uint256 lastRewardBlock; // Last block number that Obos distribution occurs.
uint256 accOboPerShare; // Accumulated Obos per share, times 1e12. See below.
uint16 depositFeeBP; // Deposit fee in basis points
}
// The Obo TOKEN!
OboToken public Obo;
// Dev address.
address public devaddr;
// Obo tokens created per block.
uint256 public OboPerBlock;
// Bonus muliplier for early Obo makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Deposit Fee address
address public feeAddress;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when Obo mining starts.
uint256 public startBlock;
mapping(address => address) public referrers; // account_address -> referrer_address
mapping(address => uint256) public referredCount; // referrer_address -> num_of_referred
event Referral(address indexed referrer, address indexed farmer);
event ReferralPaid(address indexed user,address indexed userTo, uint256 reward);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
OboToken _Obo,
address _devaddr,
address _feeAddress,
uint256 _OboPerBlock,
uint256 _startBlock
) public {
Obo = _Obo;
devaddr = _devaddr;
feeAddress = _feeAddress;
OboPerBlock = _OboPerBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accOboPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
// Update the given pool's Obo allocation point and deposit fee. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
// View function to see pending Obos on frontend.
function pendingObo(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accOboPerShare = pool.accOboPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 OboReward = multiplier.mul(OboPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accOboPerShare = accOboPerShare.add(OboReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accOboPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 OboReward = multiplier.mul(OboPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
Obo.mint(devaddr, OboReward.div(10));
Obo.mint(address(this), OboReward);
pool.accOboPerShare = pool.accOboPerShare.add(OboReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for Obo allocation.
function deposit(uint256 _pid, uint256 _amount,address referrer) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (_amount>0 && referrer != address(0)) {
setRefFriend(msg.sender, referrer);
}
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accOboPerShare).div(1e12).sub(user.rewardDebt);
uint256 toReferral = pending.mul(2).div(100);// 2%
if(pending > 0) {
referrer = getRefFriend(msg.sender);
if (referrer != address(0)) { // send commission to referrer
Obo.mint(referrer, toReferral);
emit ReferralPaid(msg.sender, referrer,toReferral);
}
safeOboTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
}else{
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accOboPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accOboPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeOboTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accOboPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe Obo transfer function, just in case if rounding error causes pool to not have enough Obos.
function safeOboTransfer(address _to, uint256 _amount) internal {
uint256 OboBal = Obo.balanceOf(address(this));
if (_amount > OboBal) {
Obo.transfer(_to, OboBal);
} else {
Obo.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function setFeeAddress(address _feeAddress) public{
require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
feeAddress = _feeAddress;
}
//Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _OboPerBlock) public onlyOwner {
massUpdatePools();
OboPerBlock = _OboPerBlock;
}
function setRefFriend(address farmer, address referrer) internal {
if (referrers[farmer] == address(0) && referrer != address(0)) {
referrers[farmer] = referrer;
referredCount[referrer] += 1;
emit Referral(referrer, farmer);
}
}
function getRefFriend(address farmer) public view returns (address) {
return referrers[farmer];
}
}
|
View function to see pending Obos on frontend.
|
function pendingObo(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accOboPerShare = pool.accOboPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 OboReward = multiplier.mul(OboPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accOboPerShare = accOboPerShare.add(OboReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accOboPerShare).div(1e12).sub(user.rewardDebt);
}
| 2,431,667 |
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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[] memory account) internal {
for(uint256 i=0; i<account.length; i++) {
require(!has(role, account[i]), "Roles: account already has role");
role.bearer[account[i]] = 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];
}
}
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address[] account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
address[] memory admins = new address[](1);
admins[0] = _msgSender();
_addWhitelistAdmin(admins);
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address[] memory account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function _addWhitelistAdmin(address[] memory account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is Context, WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address[] account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted(address _user) {
require(isWhitelisted(_user), "WhitelistedRole: caller does not have the Whitelisted role");
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address[] memory account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function _addWhitelisted(address[] memory account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
contract MinterRole is Context, WhitelistAdminRole {
using Roles for Roles.Role;
event MinterAdded(address[] account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
address[] memory admins = new address[](1);
admins[0] = _msgSender();
_addMinter(admins);
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address[] memory account) public onlyWhitelistAdmin {
_addMinter(account);
}
function removeMinter(address account) public onlyWhitelistAdmin {
_removeMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address[] memory account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, WhitelistedRole {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => uint256) public lockedUntil;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 public lockUpPeriod;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint _lockUpPeriod) public {
_name = name;
_symbol = symbol;
_decimals = 18;
lockUpPeriod = _lockUpPeriod;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public onlyWhitelisted(msg.sender) onlyWhitelisted(recipient) virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public onlyWhitelisted(msg.sender) onlyWhitelisted(spender) virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public onlyWhitelisted(sender) onlyWhitelisted(recipient) virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
chekTransferable(sender);
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
lockedUntil[account] = (block.timestamp).add(lockUpPeriod);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
// Update lockUpPeriod
function updateLockUpPeriod(uint256 _lockUpPeriod) public onlyWhitelistAdmin {
lockUpPeriod = _lockUpPeriod;
}
function chekTransferable(address _user) internal view {
require(lockedUntil[_user] <= block.timestamp, "Lock amount: amount is in lock state");
}
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public onlyWhitelistAdmin virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public onlyWhitelistAdmin virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
abstract contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter onlyWhitelisted(account) returns (bool) {
_mint(account, amount);
return true;
}
}
contract BroxToken is ERC20, Ownable, ERC20Mintable, ERC20Burnable {
string public IssuerName = "Brox Equity Ltd.";
string public BusinessNumber = "720685536";
string public Province = "British Columbia";
string public Country = "Canada";
string public Website = "www.broxequity.com";
string public Legend = "Unless permitted under securities legislation, the holder of this security must not trade the security before the date that is 4 months and a day after the later of (i) [the Closing Date (as defined herein)], and (ii) the date the issuer became a reporting issuer in any province or territory.";
string public Legend_US = "THE SECURITIES REPRESENTED HEREBY HAVE NOT BEEN REGISTERED UNDER THE UNITED STATES SECURITIES ACT OF 1933, AS AMENDED (THE “U.S. SECURITIES ACT”), OR THE SECURITIES LAWS OF ANY STATE OF THE UNITED STATES. THE HOLDER HEREOF, BY PURCHASING SUCH SECURITIES, AGREES FOR THE BENEFIT OF BROX EQUITY LTD. (THE “CORPORATION”) THAT SUCH SECURITIES MAY BE OFFERED, SOLD, PLEDGED OR OTHERWISE TRANSFERRED, DIRECTLY OR INDIRECTLY, ONLY (A) TO THE CORPORATION, (B) IN COMPLIANCE WITH RULE 904 OF REGULATION S UNDER THE U.S. SECURITIES ACT, (C) IN A TRANSACTION EXEMPT FROM REGISTRATION UNDER THE U.S. SECURITIES ACT PURSUANT TO RULE 144 UNDER THE U.S. SECURITIES ACT, IF AVAILABLE, OR (D) IN A TRANSACTION THAT DOES NOT REQUIRE REGISTRATION UNDER THE U.S. SECURITIES ACT OR ANY APPLICABLE UNITED STATES STATE SECURITIES LAWS, PROVIDED THAT IN THE CASE OF (B) ABOVE THE SELLER FURNISHES TO THE CORPORATION AND ITS TRANSFER AGENT A CERTIFICATE IN THE FORM PRESCRIBED BY THE CORPORATION EVIDENCING COMPLIANCE WITH RULE 904 OF REGULATION S, AND PROVIDED FURTHER THAT IN THE CASE OF (C) AND (D) ABOVE THE SELLER FURNISHES TO THE CORPORATION AND ITS TRANSFER AGENT AN OPINION OF COUNSEL OF RECOGNIZED STANDING IN FORM AND SUBSTANCE REASONABLY SATISFACTORY TO THE CORPORATION TO SUCH EFFECT.";
constructor(uint _lockUpPeriod) public ERC20("Brox Token", "BROX", _lockUpPeriod) {
}
}
|
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 onlyWhitelisted(msg.sender) onlyWhitelisted(recipient) virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| 518,834 |
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
/// @title zkSync additional main contract
/// @author Matter Labs
contract AdditionalZkSync is Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal {
uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw;
pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE);
}
/// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds
/// @param _storedBlockInfo Last verified block
/// @param _owner Owner of the account
/// @param _accountId Id of the account in the tree
/// @param _proof Proof
/// @param _tokenId Verified token id
/// @param _amount Amount for owner (must be total amount, not part of it)
function performExodus(
StoredBlockInfo memory _storedBlockInfo,
address _owner,
uint32 _accountId,
uint32 _tokenId,
uint128 _amount,
uint32 _nftCreatorAccountId,
address _nftCreatorAddress,
uint32 _nftSerialId,
bytes32 _nftContentHash,
uint256[] calldata _proof
) external {
require(_accountId <= MAX_ACCOUNT_ID, "e");
require(_accountId != SPECIAL_ACCOUNT_ID, "v");
require(_tokenId < SPECIAL_NFT_TOKEN_ID, "T");
require(exodusMode, "s"); // must be in exodus mode
require(!performedExodus[_accountId][_tokenId], "t"); // already exited
require(storedBlockHashes[totalBlocksExecuted] == hashStoredBlockInfo(_storedBlockInfo), "u"); // incorrect stored block info
bool proofCorrect = verifier.verifyExitProof(
_storedBlockInfo.stateHash,
_accountId,
_owner,
_tokenId,
_amount,
_nftCreatorAccountId,
_nftCreatorAddress,
_nftSerialId,
_nftContentHash,
_proof
);
require(proofCorrect, "x");
if (_tokenId <= MAX_FUNGIBLE_TOKEN_ID) {
bytes22 packedBalanceKey = packAddressAndTokenId(_owner, uint16(_tokenId));
increaseBalanceToWithdraw(packedBalanceKey, _amount);
emit WithdrawalPending(uint16(_tokenId), _owner, _amount);
} else {
require(_amount != 0, "Z"); // Unsupported nft amount
Operations.WithdrawNFT memory withdrawNftOp = Operations.WithdrawNFT(
_nftCreatorAccountId,
_nftCreatorAddress,
_nftSerialId,
_nftContentHash,
_owner,
_tokenId
);
pendingWithdrawnNFTs[_tokenId] = withdrawNftOp;
emit WithdrawalNFTPending(_tokenId);
}
performedExodus[_accountId][_tokenId] = true;
}
function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] calldata _depositsPubdata) external {
require(exodusMode, "8"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "9"); // no deposits to process
uint64 currentDepositIdx = 0;
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; ++id) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
bytes memory depositPubdata = _depositsPubdata[currentDepositIdx];
require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a");
++currentDepositIdx;
Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, uint16(op.tokenId));
pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
uint256 internal constant SECURITY_COUNCIL_THRESHOLD = $$(SECURITY_COUNCIL_THRESHOLD);
/// @notice processing new approval of decrease upgrade notice period time to zero
/// @param addr address of the account that approved the reduction of the upgrade notice period to zero
/// NOTE: does NOT revert if the address is not a security council member or number of approvals is already sufficient
function approveCutUpgradeNoticePeriod(address addr) internal {
address payable[SECURITY_COUNCIL_MEMBERS_NUMBER] memory SECURITY_COUNCIL_MEMBERS = [
$(SECURITY_COUNCIL_MEMBERS)
];
for (uint256 id = 0; id < SECURITY_COUNCIL_MEMBERS_NUMBER; ++id) {
if (SECURITY_COUNCIL_MEMBERS[id] == addr) {
// approve cut upgrade notice period if needed
if (!securityCouncilApproves[id]) {
securityCouncilApproves[id] = true;
numberOfApprovalsFromSecurityCouncil += 1;
emit ApproveCutUpgradeNoticePeriod(addr);
if (numberOfApprovalsFromSecurityCouncil >= SECURITY_COUNCIL_THRESHOLD) {
if (approvedUpgradeNoticePeriod > 0) {
approvedUpgradeNoticePeriod = 0;
emit NoticePeriodChange(approvedUpgradeNoticePeriod);
}
}
}
break;
}
}
}
/// @notice approve to decrease upgrade notice period time to zero
/// NOTE: сan only be called after the start of the upgrade
function cutUpgradeNoticePeriod(bytes32 targetsHash) external {
require(upgradeStartTimestamp != 0, "p1");
require(getUpgradeTargetsHash() == targetsHash, "p3"); // given targets are not in the active upgrade
approveCutUpgradeNoticePeriod(msg.sender);
}
/// @notice approve to decrease upgrade notice period time to zero by signatures
/// NOTE: Can accept many signatures at a time, thus it is possible
/// to completely cut the upgrade notice period in one transaction
function cutUpgradeNoticePeriodBySignature(bytes[] calldata signatures) external {
require(upgradeStartTimestamp != 0, "p2");
bytes32 targetsHash = getUpgradeTargetsHash();
// The Message includes a hash of the addresses of the contracts to which the upgrade will take place to prevent reuse signature.
bytes32 messageHash = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n110",
"Approved new ZkSync's target contracts hash\n0x",
Bytes.bytesToHexASCIIBytes(abi.encodePacked(targetsHash))
)
);
for (uint256 i = 0; i < signatures.length; ++i) {
address recoveredAddress = Utils.recoverAddressFromEthSignature(signatures[i], messageHash);
approveCutUpgradeNoticePeriod(recoveredAddress);
}
}
/// @return hash of the concatenation of targets for which there is an upgrade
/// NOTE: revert if upgrade is not active at this moment
function getUpgradeTargetsHash() internal returns (bytes32) {
// Get the addresses of contracts that are being prepared for the upgrade.
address gatekeeper = $(UPGRADE_GATEKEEPER_ADDRESS);
(bool success0, bytes memory newTarget0) = gatekeeper.staticcall(
abi.encodeWithSignature("nextTargets(uint256)", 0)
);
(bool success1, bytes memory newTarget1) = gatekeeper.staticcall(
abi.encodeWithSignature("nextTargets(uint256)", 1)
);
(bool success2, bytes memory newTarget2) = gatekeeper.staticcall(
abi.encodeWithSignature("nextTargets(uint256)", 2)
);
require(success0 && success1 && success2, "p5"); // failed to get new targets
address newTargetAddress0 = abi.decode(newTarget0, (address));
address newTargetAddress1 = abi.decode(newTarget1, (address));
address newTargetAddress2 = abi.decode(newTarget2, (address));
return keccak256(abi.encodePacked(newTargetAddress0, newTargetAddress1, newTargetAddress2));
}
/// @notice Set data for changing pubkey hash using onchain authorization.
/// Transaction author (msg.sender) should be L2 account address
/// @notice New pubkey hash can be reset, to do that user should send two transactions:
/// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer.
/// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`.
/// @param _pubkeyHash New pubkey hash
/// @param _nonce Nonce of the change pubkey L2 transaction
function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external {
requireActive();
require(_pubkeyHash.length == PUBKEY_HASH_BYTES, "y"); // PubKeyHash should be 20 bytes.
if (authFacts[msg.sender][_nonce] == bytes32(0)) {
authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash);
} else {
uint256 currentResetTimer = authFactsResetTimer[msg.sender][_nonce];
if (currentResetTimer == 0) {
authFactsResetTimer[msg.sender][_nonce] = block.timestamp;
} else {
require(block.timestamp.sub(currentResetTimer) >= AUTH_FACT_RESET_TIMELOCK, "z");
authFactsResetTimer[msg.sender][_nonce] = 0;
authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash);
}
}
}
/// @notice Reverts unverified blocks
function revertBlocks(StoredBlockInfo[] calldata _blocksToRevert) external {
requireActive();
governance.requireActiveValidator(msg.sender);
uint32 blocksCommitted = totalBlocksCommitted;
uint32 blocksToRevert = Utils.minU32(uint32(_blocksToRevert.length), blocksCommitted - totalBlocksExecuted);
uint64 revertedPriorityRequests = 0;
for (uint32 i = 0; i < blocksToRevert; ++i) {
StoredBlockInfo memory storedBlockInfo = _blocksToRevert[i];
require(storedBlockHashes[blocksCommitted] == hashStoredBlockInfo(storedBlockInfo), "r"); // incorrect stored block info
delete storedBlockHashes[blocksCommitted];
--blocksCommitted;
revertedPriorityRequests += storedBlockInfo.priorityOperations;
}
totalBlocksCommitted = blocksCommitted;
totalCommittedPriorityRequests -= revertedPriorityRequests;
if (totalBlocksCommitted < totalBlocksProven) {
totalBlocksProven = totalBlocksCommitted;
}
emit BlocksRevert(totalBlocksExecuted, blocksCommitted);
}
}
|
approve to decrease upgrade notice period time to zero NOTE: сan only be called after the start of the upgrade
|
function cutUpgradeNoticePeriod(bytes32 targetsHash) external {
require(upgradeStartTimestamp != 0, "p1");
approveCutUpgradeNoticePeriod(msg.sender);
}
| 952,869 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
//
// ███████╗██╗███╗░░██╗░█████╗░██╗░░░░░██████╗░░█████╗░░██████╗██╗░░░██╗
// ██╔════╝██║████╗░██║██╔══██╗██║░░░░░██╔══██╗██╔══██╗██╔════╝██║░░░██║
// █████╗░░██║██╔██╗██║███████║██║░░░░░██████╦╝██║░░██║╚█████╗░██║░░░██║
// ██╔══╝░░██║██║╚████║██╔══██║██║░░░░░██╔══██╗██║░░██║░╚═══██╗██║░░░██║
// ██║░░░░░██║██║░╚███║██║░░██║███████╗██████╦╝╚█████╔╝██████╔╝╚██████╔╝
// ╚═╝░░░░░╚═╝╚═╝░░╚══╝╚═╝░░╚═╝╚══════╝╚═════╝░░╚════╝░╚═════╝░░╚═════╝░
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
contract FinalBosu is ERC721Enumerable, Ownable {
using SafeMath for uint256;
using SafeCast for uint256;
using Strings for uint256;
using Address for address;
enum TokenStatus { NEW, REQUESTED, FULFILLED }
string private _baseUri;
uint256 public constant MAX_SUPPLY = 555;
uint256 public PRICE = 0.3 ether;
uint256 public MAX_MINT = 2;
uint256 public WHITELIST_MAX_MINT = 2;
/**
* 0: Sale is not active
* 1: Private sale
* 2: Public sale
*/
uint8 public saleStatus = 0;
mapping(address => uint256) public whitelist;
mapping(uint16 => TokenStatus) public tokenStatus;
event ChangeTokenStatus(address indexed _address, uint256 indexed _tokenId, TokenStatus _prevStatus, TokenStatus _currStatus, string _meta);
constructor() ERC721("FinalBosu", "FINALBOSU") {}
/**
* Returns base URI of tokens.
*/
function _baseURI() internal view override returns (string memory) {
return _baseUri;
}
/**
* Set or change baseUri.
*/
function setBaseURI(string calldata newBaseURI) external onlyOwner {
_baseUri = newBaseURI;
}
/**
* Set price.
*/
function setPrice(uint256 _price) external onlyOwner {
PRICE = _price;
}
/**
* Set max mint count.
*/
function setMaxMint(uint256 _maxMint) external onlyOwner {
MAX_MINT = _maxMint;
}
/**
* Set max mint count for whitelisted users.
*/
function setWhitelistMaxMint(uint256 _whitelistMaxMint) external onlyOwner {
WHITELIST_MAX_MINT = _whitelistMaxMint;
}
/**
* Set sale status.
*/
function setSaleStatus(uint8 _saleStatus) external onlyOwner {
saleStatus = _saleStatus;
}
/**
* Add addresses to whitelist.
*/
function addWhitelists(address[] calldata addresses) external onlyOwner {
for (uint16 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "FinalBosu: invalid address");
whitelist[addresses[i]] = WHITELIST_MAX_MINT;
}
}
/**
* Internal function to set token id
*/
function _setTokenStatus(uint256 tokenId, TokenStatus status, string memory meta) internal {
require(_exists(tokenId), "FinalBosu: invalid token id");
if (tokenStatus[tokenId.toUint16()] != status) {
TokenStatus prevStatus = tokenStatus[tokenId.toUint16()];
tokenStatus[tokenId.toUint16()] = status;
emit ChangeTokenStatus(_msgSender(), tokenId, prevStatus, status, meta);
}
}
/**
* Request ticket for custom drawing with photo url
*/
function request(uint256 tokenId, string calldata uploadImageUrl) external {
require(_msgSender() == ownerOf(tokenId), "FinalBosu: only token owner can request");
require(tokenStatus[tokenId.toUint16()] == TokenStatus.NEW, "FinalBosu: cannot use this token to request");
require(bytes(uploadImageUrl).length > 0, "FinalBosu: uploadImageUrl cannot be empty");
// TODO: check if uploadImageUrl is valid url
_setTokenStatus(tokenId, TokenStatus.REQUESTED, uploadImageUrl);
}
/**
* Fulfill multiple tickets
*/
function fulfillMultiple(uint256[] calldata tokenIds) external onlyOwner {
for (uint16 i = 0; i < tokenIds.length; i++) {
_fulfill(tokenIds[i]);
}
}
/**
* Fulfull a ticket
*/
function fulfill(uint256 tokenId) external onlyOwner {
_fulfill(tokenId);
}
/**
* Fullfill a ticket
*/
function _fulfill(uint256 tokenId) internal {
require(tokenStatus[tokenId.toUint16()] == TokenStatus.REQUESTED, "FinalBosu: invalid token status");
_setTokenStatus(tokenId, TokenStatus.FULFILLED, "");
}
/**
* Mint in public sale
*/
function mint(uint quantity) external payable {
require(saleStatus == 2, "FinalBosu: sale is not active");
require(quantity > 0, "FinalBosu: invalid quantity");
require(quantity <= MAX_MINT, "FinalBosu: quantity exceeds max mint");
require(totalSupply().add(quantity) <= MAX_SUPPLY, "FinalBosu: quantity exceed max supply");
require(PRICE.mul(quantity) <= msg.value, "FinalBosu: insufficient value");
for (uint i = 0; i < quantity; i++) {
_safeMint(_msgSender(), totalSupply() + 1);
}
}
/**
* Mint in private sale
*/
function mintPresale(uint quantity) external payable {
require(saleStatus == 1, "FinalBosu: sale is not active");
require(quantity > 0, "FinalBosu: invalid quantity");
require(whitelist[_msgSender()] >= quantity, "FinalBosu: not allowed to mint");
require(totalSupply().add(quantity) <= MAX_SUPPLY, "FinalBosu: quantity exceed max supply");
require(PRICE.mul(quantity) <= msg.value, "FinalBosu: insufficient value");
whitelist[_msgSender()] -= quantity;
for (uint i = 0; i < quantity; i++) {
_safeMint(_msgSender(), totalSupply() + 1);
}
}
/**
* Mint for admin
*/
function mintReserve(uint quantity, address to) external onlyOwner {
require(quantity > 0, "FinalBosu: invalid quantity");
require(to != address(0), "FinalBosu: invalid address");
require(totalSupply().add(quantity) <= MAX_SUPPLY, "FinalBosu: quantity exceed max supply");
for (uint i = 0; i < quantity; i++) {
_safeMint(to, totalSupply() + 1);
}
}
/**
* Withdraw values in this contract to withdrawer address and caller must be withdrawer.
*/
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "zero balance");
payable(_msgSender()).transfer(balance);
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 index; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
/**
* Check if token is locked
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
require(tokenStatus[tokenId.toUint16()] != TokenStatus.REQUESTED, "FinalBosu: token is locked");
super._beforeTokenTransfer(from, to, tokenId);
}
}
|
Request ticket for custom drawing with photo url/ TODO: check if uploadImageUrl is valid url
|
function request(uint256 tokenId, string calldata uploadImageUrl) external {
require(_msgSender() == ownerOf(tokenId), "FinalBosu: only token owner can request");
require(tokenStatus[tokenId.toUint16()] == TokenStatus.NEW, "FinalBosu: cannot use this token to request");
require(bytes(uploadImageUrl).length > 0, "FinalBosu: uploadImageUrl cannot be empty");
_setTokenStatus(tokenId, TokenStatus.REQUESTED, uploadImageUrl);
}
| 546,180 |
// SPDX-License-Identifier: MIT
//
// Developed by https://1block.one
//
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: BBstaking.sol
pragma solidity ^0.8.9;
/*
Interfaces for Bohemian Bulldogs service Smart Contracts
*/
interface TokenContract {
function allowanceFor(address spender) external view returns(uint256);
function transferFrom(address _from, address _to, uint256 _value) external returns(bool);
function balanceOf(address owner) external view returns(uint); function burnFrom(address account, uint256 amount) external;
}
interface NFTContract {
function ownerOf(uint256 _tokenId) external view returns (address);
function transferFrom(address from, address to, uint tokenId) external payable;
}
/*
End of interfaces
*/
contract BulldogsStaking is ReentrancyGuard {
//// Events
event _adminSetCollectionEarnRate(uint collectionId, uint _earnRate);
event _adminSetCollectionSwapCost(uint collectionId, uint _swapRate);
event _adminSetTokensCollections(uint[] _tokenIds, uint _collectionId);
event _adminSetMinStakingPerion(uint period);
event _adminSetFreezePeriod(uint period);
event _adminSetClaimableBalance(address[] _address, uint amount);
event _adminAddBonus(address[] _address, uint amount);
event _userSetTokenCollection(uint _tokenId, uint _collectionId);
event _setTokenContract(address _address);
event _setNFTContract(address _address);
event Staked(uint tokenId);
event Unstaked(uint256 tokenId);
event BBonesClaimed(address _address, uint amount);
event bulldogUpgraded(uint tokenId);
event bulldogSwapped(uint tokenId);
// Base variables
address private _owner;
address private _tokenContractAddress;
address private _nftContractAddress;
// Minimal period before you can claim $BBONES, in blocks
uint minStakingPeriod = 930;
// Freeze after which you can claim and unstake, in blocks
uint freezePeriod = 20000;
/* Data storage:
Collections:
1 - Street
2 - Bohemian
3 - Boho
4 - Business
5 - Business Smokers
6 - Capsule
*/
// tokenId -> collectionId
mapping(uint => uint) public tokensData;
// collectionId -> minStakingPeriod earn rate
mapping(uint => uint) public earnRates;
// collectionId -> upgradeability cost in $BBONES to the next one
mapping(uint => uint) public upgradeabilityCost;
// collectionId -> swapping cost in $BBONES, for interchange your NFT inside the same collection
mapping(uint => uint) public swappingCost;
// list of claimableBalance
mapping(address => uint) public claimableBalance;
struct Staker {
// list of staked tokenIds
uint[] stakedTokens;
// tokenId -> blockNumber
mapping(uint => uint) tokenStakeBlock;
}
mapping(address => Staker) private stakeHolders;
constructor () {
_owner = msg.sender;
earnRates[1] = 1;
earnRates[2] = 2;
earnRates[3] = 8;
earnRates[4] = 24;
earnRates[5] = 36;
earnRates[6] = 0;
upgradeabilityCost[1] = 100;
upgradeabilityCost[2] = 400;
upgradeabilityCost[3] = 2400;
upgradeabilityCost[4] = 4800;
swappingCost[1] = 50;
swappingCost[2] = 200;
swappingCost[3] = 1200;
swappingCost[4] = 2400;
swappingCost[5] = 3200;
}
/*
Modifiers
*/
modifier onlyOwner {
require(msg.sender == _owner || msg.sender == address(this), "You're not owner");
_;
}
modifier staked(uint tokenId) {
require(stakeHolders[msg.sender].tokenStakeBlock[tokenId] != 0, "You have not staked this token");
_;
}
modifier notStaked(uint tokenId) {
require(stakeHolders[msg.sender].tokenStakeBlock[tokenId] == 0, "You have already staked this token");
_;
}
modifier freezePeriodPassed(uint tokenId) {
uint blockNum = stakeHolders[msg.sender].tokenStakeBlock[tokenId];
require(blockNum + freezePeriod <= block.number, "This token is freezed, try again later");
_;
}
modifier ownerOfToken(uint tokenId) {
require(msg.sender == NFTContract(_nftContractAddress).ownerOf(tokenId) || stakeHolders[msg.sender].tokenStakeBlock[tokenId] > 0, "You are not owner of this token");
_;
}
/*
End of modifiers
*/
/*
Storage-related functions
*/
// Set/reset collection's earn rate
function adminSetCollectionEarnRate(uint collectionId, uint _earnRate) external onlyOwner {
earnRates[collectionId] = _earnRate;
emit _adminSetCollectionEarnRate(collectionId, _earnRate);
}
// Set/reset collection's swap rate
function adminSetCollectionSwapCost(uint collectionId, uint _swapCost) external onlyOwner {
swappingCost[collectionId] = _swapCost;
emit _adminSetCollectionSwapCost(collectionId, _swapCost);
}
// Set/reset token's earn rate
function adminSetTokensCollections(uint[] memory _tokenIds, uint _collectionId) external onlyOwner {
for (uint i=0; i < _tokenIds.length; i++) {
tokensData[_tokenIds[i]] = _collectionId;
}
emit _adminSetTokensCollections(_tokenIds, _collectionId);
}
// Set claimableBalance to wallets
function adminSetClaimableBalance(address[] memory _address, uint amount) external onlyOwner {
for (uint i=0; i < _address.length; i++) {
claimableBalance[_address[i]] = amount;
}
emit _adminSetClaimableBalance(_address, amount);
}
// Add claimableBalance to wallets
function adminAddBonus(address[] memory _address, uint amount) public onlyOwner {
for (uint i=0; i < _address.length; i++) {
claimableBalance[_address[i]] += amount;
}
emit _adminAddBonus(_address, amount);
}
// Set collectionId for tokenId
function userSetTokenCollection(uint _tokenId, uint _collectionId) internal {
tokensData[_tokenId] = _collectionId;
emit _userSetTokenCollection(_tokenId, _collectionId);
}
// Set new minStakingPeriod
function setMinStakingPeriod(uint period) public onlyOwner {
minStakingPeriod = period;
emit _adminSetMinStakingPerion(period);
}
// Set new freezePeriod
function setFreezePeriod(uint period) public onlyOwner {
freezePeriod = period;
emit _adminSetFreezePeriod(period);
}
/*
End of storage-related functions
*/
/*
Setters
*/
function setTokenContract(address _address) public onlyOwner {
_tokenContractAddress = _address;
emit _setTokenContract(_address);
}
function setNFTContract(address _address) public onlyOwner {
_nftContractAddress = _address;
emit _setNFTContract(_address);
}
/*
End of setters
*/
/*
Getters
*/
// In how many blocks token can be unstaked
function getBlocksTillUnfreeze(uint tokenId, address _address) public view returns(uint) {
uint blocksPassed = block.number - stakeHolders[_address].tokenStakeBlock[tokenId];
if (blocksPassed >= freezePeriod) {
return 0;
}
return freezePeriod - blocksPassed;
}
function getTokenEarnRate(uint _tokenId) public view returns(uint tokenEarnRate) {
return earnRates[tokensData[_tokenId]];
}
// Get token's unrealized pnl
function getTokenUPNL(uint tokenId, address _address) public view returns(uint) {
if (stakeHolders[_address].tokenStakeBlock[tokenId] == 0) {
return 0;
}
uint tokenBlockDiff = block.number - stakeHolders[_address].tokenStakeBlock[tokenId];
//Token will not be in freeze period
if (tokenBlockDiff <= freezePeriod) {
return 0;
}
// Token has to be staked minimum number of blocks
if (tokenBlockDiff >= minStakingPeriod) {
uint quotient;
uint remainder;
// if enough blocks have passed to get at least 1 payout => proceed
(quotient, remainder) = superDivision(tokenBlockDiff, minStakingPeriod);
if (quotient > 0) {
uint blockRate = getTokenEarnRate(tokenId);
uint tokenEarnings = blockRate * quotient;
return tokenEarnings;
}
}
return 0;
}
// Returns total unrealized pnl
function getTotalUPNL(address _address) public view returns(uint) {
uint totalUPNL = 0;
uint tokensCount = stakeHolders[_address].stakedTokens.length;
for (uint i = 0; i < tokensCount; i++) {
totalUPNL += getTokenUPNL(stakeHolders[_address].stakedTokens[i], _address);
}
return totalUPNL;
}
/*
End of getters
*/
/*
Staking functions
*/
function stake(uint tokenId, uint tokenCollection) public nonReentrant notStaked(tokenId) ownerOfToken(tokenId) {
// Setting token's collection if it wasn't set
if (tokensData[tokenId] == 0) {
userSetTokenCollection(tokenId, tokenCollection);
}
// Checking bulldog's collection to see whether it's upgradeable
require(tokensData[tokenId] >= 1 && tokensData[tokenId] < 6, "You cannot stake this bulldog");
// Making approved transfer from the main NFT contract
NFTContract(_nftContractAddress).transferFrom(msg.sender, address(this), tokenId);
// Writing changes to DB
stakeHolders[msg.sender].tokenStakeBlock[tokenId] = block.number + 1;
stakeHolders[msg.sender].stakedTokens.push(tokenId);
emit Staked(tokenId);
}
function unstake(uint256 tokenId) public nonReentrant ownerOfToken(tokenId) staked(tokenId) freezePeriodPassed(tokenId) {
// Adding unclaimed $BBONES to claimableBalance
claimableBalance[msg.sender] += getTokenUPNL(tokenId, msg.sender);
stakeHolders[msg.sender].tokenStakeBlock[tokenId] = 0;
uint tokensCount = stakeHolders[msg.sender].stakedTokens.length;
uint[] memory newStakedTokens = new uint[](tokensCount - 1);
uint j = 0;
for (uint i = 0; i < tokensCount; i++) {
if (stakeHolders[msg.sender].stakedTokens[i] != tokenId) {
newStakedTokens[j] = stakeHolders[msg.sender].stakedTokens[i];
j += 1;
}
}
stakeHolders[msg.sender].stakedTokens = newStakedTokens;
// Making approved transfer NFT back to its owner
NFTContract(_nftContractAddress).transferFrom(address(this), msg.sender, tokenId);
emit Unstaked(tokenId);
}
// divides two numbers and returns quotient & remainder
function superDivision(uint numerator, uint denominator) internal pure returns(uint quotient, uint remainder) {
quotient = numerator / denominator;
remainder = numerator - denominator * quotient;
}
// Call to get you staking reward
function claimBBones(address _address) public nonReentrant {
uint amountToPay = 0;
uint tokensCount = stakeHolders[_address].stakedTokens.length;
for (uint i = 0; i < tokensCount; i++) {
uint tokenId = stakeHolders[_address].stakedTokens[i];
uint tokenBlockDiff = block.number - stakeHolders[_address].tokenStakeBlock[tokenId];
// Token has to be staked minimum number of blocks
if (tokenBlockDiff >= minStakingPeriod && stakeHolders[_address].tokenStakeBlock[tokenId] + freezePeriod <= block.number) {
uint quotient;
uint remainder;
// if enough blocks have passed to get at least 1 payout => proceed
(quotient, remainder) = superDivision(tokenBlockDiff, minStakingPeriod);
if (quotient > 0) {
uint blockRate = getTokenEarnRate(tokenId);
uint tokenEarnings = blockRate * quotient;
amountToPay += tokenEarnings;
stakeHolders[_address].tokenStakeBlock[tokenId] = block.number - remainder + 1;
}
}
}
// Claiming claimableBalance if any
if (claimableBalance[_address] > 0) {
amountToPay += claimableBalance[_address];
claimableBalance[_address] = 0;
}
TokenContract(_tokenContractAddress).transferFrom(_tokenContractAddress, _address, amountToPay);
emit BBonesClaimed(_address, amountToPay);
}
// Get user's list of staked tokens
function stakedTokensOf(address _address) public view returns (uint[] memory) {
return stakeHolders[_address].stakedTokens;
}
/*
End of staking
*/
/*
Upgrading
*/
function upgradeBulldog(uint tokenId, uint collectionId, uint upgradeType) public nonReentrant ownerOfToken(tokenId) {
/*
Upgrade types:
1 - to the next collection
2 - swap inside the same collection
*/
// Setting token's collection if it wasn't set
if (tokensData[tokenId] == 0) {
tokensData[tokenId] = collectionId;
}
// Checking bulldog's collection to see whether it's upgradeable
require(tokensData[tokenId] >= 1 && tokensData[tokenId] < 5, "Your bulldog cannot be upgraded further");
// User has emough $BBONES to pay for the upgrade
require(TokenContract(_tokenContractAddress).balanceOf(msg.sender) >= upgradeabilityCost[tokensData[tokenId]], "You don't have enough $BBONES");
// Upgrading
if (upgradeType == 1) {
// If token is staked: save his UPNL and reset
if (stakeHolders[msg.sender].tokenStakeBlock[tokenId] > 0) {
// Adding unclaimed $BBONES to claimableBalanceses
claimableBalance[msg.sender] += getTokenUPNL(tokenId, msg.sender);
stakeHolders[msg.sender].tokenStakeBlock[tokenId] = block.number + 1;
}
TokenContract(_tokenContractAddress).burnFrom(msg.sender, upgradeabilityCost[tokensData[tokenId]]);
tokensData[tokenId] += 1;
emit bulldogUpgraded(tokenId);
}
// Swapping
if (upgradeType == 2) {
TokenContract(_tokenContractAddress).burnFrom(msg.sender, upgradeabilityCost[tokensData[tokenId]]);
emit bulldogSwapped(tokenId);
}
}
/*
End of upgrading
*/
}
//
// Developed by https://1block.one
//
|
Returns total unrealized pnl
|
function getTotalUPNL(address _address) public view returns(uint) {
uint totalUPNL = 0;
uint tokensCount = stakeHolders[_address].stakedTokens.length;
for (uint i = 0; i < tokensCount; i++) {
totalUPNL += getTokenUPNL(stakeHolders[_address].stakedTokens[i], _address);
}
return totalUPNL;
}
| 5,421,431 |
./partial_match/1/0xE7184065E396e071Cf55edef5C74A1D2d05B8849/sources/CarMechanics.sol
|
Setup base URI Setup URI
|
function setupBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
| 4,114,758 |
pragma solidity ^0.5.0;
contract Adoption {
address[16] public adopters;
uint[16] public portugues;
uint[16] public matematica;
uint[16] public ciencia;
// Adopting a pet
function adopt(uint petId, uint petPo, uint petMa, uint petCi) public returns (uint) {
require(petId >= 0 && petId <= 15);
require(petPo >= 0 && petPo <= 10);
require(petMa >= 0 && petMa <= 10);
require(petCi >= 0 && petCi <= 10);
adopters[petId] = msg.sender;
portugues[petId] = petPo;
matematica[petId] = petMa;
ciencia[petId] = petCi;
return petId;
}
// Retrieving the adopters
function getAdopters() public view returns (address[16] memory) {
return adopters;
}
function getPortugues() public view returns (uint[16] memory) {
return portugues;
}
function getMatematica() public view returns (uint[16] memory) {
return matematica;
}
function getCiencia() public view returns (uint[16] memory) {
return ciencia;
}
}
|
Retrieving the adopters
|
function getAdopters() public view returns (address[16] memory) {
return adopters;
}
| 14,050,081 |
./partial_match/7700/0xdc0aa5ae2867F5FD41Ba6FDfea072998291Ee742/sources/src/Note.sol
|
set the New Accountant
|
function _setAccountantAddress(address accountant_) external {
require(msg.sender == admin);
accountant = accountant_;
if (balanceOf(accountant) != type(uint).max) {
_mint_to_Accountant(accountant);
}
}
| 3,505,492 |
./full_match/97/0x8B4032b71C804517D54878d78730c230F768Ad57/sources/tests/BSC ChainLinkTests/PWA.sol
|
Returns project Data for a given projectAddress
|
function getProjectData(
address _address
) public view returns (PWProject memory) {
uint256 id = projectsIds[_address];
return projects[id];
}
| 5,018,659 |
./partial_match/1/0x1da8E62726A18d3a563AF8c10fC44416A89E9BAc/sources/PaymentProcessor.sol
|
recordDealRefundReason creates an event of not paid deal that was cancelled _orderId Identifier of deal's order _clientAddress Address of client's account _clientReputation Updated reputation of the client _merchantReputation Updated reputation of the merchant _dealHash Hashcode of the deal, describing the order (used for deal verification) _refundReason deal refund reason (text)/
|
function recordDealRefundReason(
uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _refundReason)
external onlyMonetha
{
emit DealRefundReason(
_orderId,
_clientAddress,
_clientReputation,
_merchantReputation,
_dealHash,
_refundReason
);
}
| 3,724,627 |
/*
Implement ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
*/
pragma solidity ^0.4.25;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address public _owner;
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Ownable: new owner is zero address");
emit OwnershipTransferred(_owner, _newOwner);
_owner = _newOwner;
}
}
contract Token {
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 amount) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view 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 {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 amount) {
require(_owner != address(0), "Zero owner address");
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0), "Zero destination address");
require(_to != address(this), "Contract address");
require(_value > 0, "Transferred value <= 0");
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_from != address(0), "Zero source address");
require(_to != address(0), "Zero destination address");
require(_to != address(this), "Contract address");
require(_value > 0, "Transferred value <= 0");
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
balances[_from] = SafeMath.sub(balances[_from], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require(_spender != address(0), "Zero spender address");
require(_spender != address(this), "Contract address");
require(_value >= 0, "Approved value < 0");
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
require(_owner != address(0), "Zero owner address");
require(_spender != address(0), "Zero spender address");
return allowed[_owner][_spender];
}
}
contract CustomizedToken is StandardToken, Ownable {
string public name;
string public symbol;
uint8 public decimals;
uint256 public _rate = 1000000000000000000;
constructor(
uint256 _initialAmount,
string memory _tokenName,
string memory _tokenSymbol,
uint8 _decimalUnits
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
emit Transfer(address(0), _owner, totalSupply);
}
/* This notifies clients about the amount burnt */
event Burn(address indexed _from, uint256 _value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed _from, uint256 _value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed _from, uint256 _value);
/* This notifies clients about the rate change */
event ChangeRate(uint256 _current, uint256 _new);
/* Fallback function */
function() external payable {}
/* Token that can be irreversibly burned (destroyed) */
function burn(uint256 _value) public returns (bool success) {
require(_value > 0, "Burned value <= 0");
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
totalSupply = SafeMath.sub(totalSupply, _value);
emit Burn(msg.sender, _value);
return true;
}
/* Token that can be minted (created) */
function mint(uint _value) public onlyOwner returns (bool success) {
require(_value > 0, "Minted value <= 0");
totalSupply = SafeMath.add(totalSupply, _value);
balances[_owner] = SafeMath.add(balances[_owner], _value);
emit Transfer(address(0), _owner, _value);
return true;
}
/* Return the frozen amount */
mapping (address => uint256) private freezes;
function freezeOf(address _owner) public view returns (uint256 amount) {
require(_owner != address(0), "Zero owner address");
return freezes[_owner];
}
/* Token that can be frozen (locked) */
function freeze(uint256 _value) public returns (bool success) {
require(_value > 0, "Frozen value <= 0");
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
freezes[msg.sender] = SafeMath.add(freezes[msg.sender], _value);
emit Freeze(msg.sender, _value);
return true;
}
/* Token that can be unfrozen (unlocked) */
function unfreeze(uint256 _value) public returns (bool success) {
require(_value > 0, "Unfrozen value <= 0");
freezes[msg.sender] = SafeMath.sub(freezes[msg.sender], _value);
balances[msg.sender] = SafeMath.add(balances[msg.sender], _value);
emit Unfreeze(msg.sender, _value);
return true;
}
/* Ether withdraw function */
function withdrawEther() public onlyOwner {
_owner.transfer(address(this).balance);
}
/* Buying tokens with Ethers (unit: wei) */
function buyTokens() public payable returns (bool success) {
uint256 _value = SafeMath.div(msg.value, _rate);
require(_value > 0, "Purchased tokens <= 0");
balances[_owner] = SafeMath.sub(balances[_owner], _value);
balances[msg.sender] = SafeMath.add(balances[msg.sender], _value);
emit Transfer(_owner, msg.sender, _value);
return true;
}
/* Changing rate between token and Ether (unit: wei) */
function changeRate(uint256 _newRate) public onlyOwner returns (bool success) {
require(_newRate > 0, "New rate <= 0");
emit ChangeRate(_rate, _newRate);
_rate = _newRate;
return true;
}
}
|
Token that can be minted (created) /
|
function mint(uint _value) public onlyOwner returns (bool success) {
require(_value > 0, "Minted value <= 0");
totalSupply = SafeMath.add(totalSupply, _value);
balances[_owner] = SafeMath.add(balances[_owner], _value);
emit Transfer(address(0), _owner, _value);
return true;
}
| 12,575,680 |
pragma solidity 0.7.5;
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }("");
require(success, "Flush failed");
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, "Only Parent");
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), "Already initialized");
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
require(
instance.transfer(parentAddress, forwarderBalance),
"Token flush failed"
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }("");
require(success, "Flush failed");
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
Flush the entire balance of the contract to the parent address./
|
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
require(success, "Flush failed");
emit ForwarderDeposited(msg.sender, value, msg.data);
}
| 1,370,759 |
./full_match/5/0x8Ca03f2f040f8f8BdfCa0Df83E68460FFE78f8DF/sources/contracts/CompanyRegistry.sol
|
Function to get information about a company
|
function getCompany(
address _company
)
public
view
onlyAdminOrOwner(_company)
returns (
bool approved,
uint256 approvalDate,
address approvedBy,
address owner,
string memory companyName,
string memory companyAddress,
uint256 totalSales
)
{
Company storage company = companies[_company];
approved = company.approved;
approvalDate = company.approvalDate;
approvedBy = company.approvedBy;
owner = company.owner;
totalSales = company.totalSales;
companyName = company.companyName;
companyAddress = company.companyAddress;
}
| 1,859,983 |
./partial_match/1/0x2736af1C70B60501EF5a18690C77cC82EA80Da0b/sources/Dividend.sol
|
generate the uniswap pair path of token -> weth
|
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
| 2,627,712 |
./full_match/1/0x1a4076c26842501da0d6D879dd7A78810f8DA727/sources/contracts/Timeout.sol
|
privatesalesmint mint on private sale. Requirements: - Only whitelisted address can mint/
|
function privatesalesmint(
DataLibrarry.Coupon memory coupon,
DataLibrarry.CouponType couponType,
DataLibrarry.CouponTypeCount memory count
)
external
{
if(phase != DataLibrarry.SalePhase.Phase02) revert InvalidPhase();
if(isFreeMinted[msg.sender] == true) revert AlreadyUsePrivateSalesMint();
FunctionLib.verifyCoupon(WhiteListSigner, coupon, couponType, count);
if (couponType == DataLibrarry.CouponType.WhiteListSales)
revert InvalidWhitelist();
uint16 quantity;
unchecked {
quantity =
(count.BasicCount * 2)
+ (count.UltrarareCount * 3)
+ (count.LegendaireCount * 4)
+ (count.eggCount * 2);
}
if (indexMint + quantity > maxSupplyPrivateSale + maxSupplyPremint) revert MaxSupplyPrivateSaleReach();
_mint(msg.sender, quantity);
unchecked {
index += quantity;
indexMint += quantity;
isFreeMinted[msg.sender] = true;
}
}
| 8,435,889 |
pragma solidity ^0.4.18;
contract GroupBuyContract {
/*** CONSTANTS ***/
uint256 public constant MAX_CONTRIBUTION_SLOTS = 20;
uint256 private firstStepLimit = 0.053613 ether;
uint256 private secondStepLimit = 0.564957 ether;
/*** DATATYPES ***/
// @dev A Group is created for all the contributors who want to contribute
// to the purchase of a particular token.
struct Group {
// Array of addresses of contributors in group
address[] contributorArr;
// Maps address to an address's position (+ 1) in the contributorArr;
// 1 is added to the position because zero is the default value in the mapping
mapping(address => uint256) addressToContributorArrIndex;
mapping(address => uint256) addressToContribution; // user address to amount contributed
bool exists; // For tracking whether a group has been initialized or not
uint256 contributedBalance; // Total amount contributed
uint256 purchasePrice; // Price of purchased token
}
// @dev A Contributor record is created for each user participating in
// this group buy contract. It stores the group ids the user contributed to
// and a record of their sale proceeds.
struct Contributor {
// Maps tokenId to an tokenId's position (+ 1) in the groupArr;
// 1 is added to the position because zero is the default value in the mapping
mapping(uint256 => uint) tokenIdToGroupArrIndex;
// Array of tokenIds contributed to by a contributor
uint256[] groupArr;
bool exists;
// Ledger for withdrawable balance for this user.
// Funds can come from excess paid into a groupBuy,
// or from withdrawing from a group, or from
// sale proceeds from a token.
uint256 withdrawableBalance;
}
/*** EVENTS ***/
/// Admin Events
// @dev Event noting commission paid to contract
event Commission(uint256 _tokenId, uint256 amount);
/// Contract Events
// @dev Event signifiying that contract received funds via fallback fn
event FundsReceived(address _from, uint256 amount);
/// User Events
// @dev Event marking funds deposited into user _to's account
event FundsDeposited(address _to, uint256 amount);
// @dev Event marking a withdrawal of amount by user _to
event FundsWithdrawn(address _to, uint256 amount);
// @dev Event noting an interest distribution for user _to for token _tokenId.
// Token Group will not be disbanded
event InterestDeposited(uint256 _tokenId, address _to, uint256 amount);
// @dev Event for when a contributor joins a token group _tokenId
event JoinGroup(
uint256 _tokenId,
address contributor,
uint256 groupBalance,
uint256 contributionAdded
);
// @dev Event for when a contributor leaves a token group
event LeaveGroup(
uint256 _tokenId,
address contributor,
uint256 groupBalance,
uint256 contributionSubtracted
);
// @dev Event noting sales proceeds distribution for user _to from sale of token _tokenId
event ProceedsDeposited(uint256 _tokenId, address _to, uint256 amount);
// @dev Event for when a token group purchases a token
event TokenPurchased(uint256 _tokenId, uint256 balance);
/*** STORAGE ***/
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress1;
address public cooAddress2;
address public cooAddress3;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
bool public forking = false;
uint256 public activeGroups;
uint256 public commissionBalance;
uint256 private distributionNumerator;
uint256 private distributionDenominator;
CelebrityToken public linkedContract;
/// @dev A mapping from token IDs to the group associated with that token.
mapping(uint256 => Group) private tokenIndexToGroup;
// @dev A mapping from owner address to available balance not held by a Group.
mapping(address => Contributor) private userAddressToContributor;
/*** ACCESS MODIFIERS ***/
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(
msg.sender == cooAddress1 ||
msg.sender == cooAddress2 ||
msg.sender == cooAddress3
);
_;
}
/// @dev Access modifier for contract managers only functionality
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress1 ||
msg.sender == cooAddress2 ||
msg.sender == cooAddress3 ||
msg.sender == cfoAddress
);
_;
}
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS NOT in forking mode
modifier whenNotForking() {
require(!forking);
_;
}
/// @dev Modifier to allow actions only when the contract IS in forking mode
modifier whenForking {
require(forking);
_;
}
/*** CONSTRUCTOR ***/
function GroupBuyContract(address contractAddress, uint256 numerator, uint256 denominator) public {
ceoAddress = msg.sender;
cooAddress1 = msg.sender;
cooAddress2 = msg.sender;
cooAddress3 = msg.sender;
cfoAddress = msg.sender;
distributionNumerator = numerator;
distributionDenominator = denominator;
linkedContract = CelebrityToken(contractAddress);
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Fallback fn for receiving ether
function() external payable {
FundsReceived(msg.sender, msg.value);
}
/** Action Fns **/
/// @notice Backup function for activating token purchase
/// requires sender to be a member of the group or CLevel
/// @param _tokenId The ID of the Token group
function activatePurchase(uint256 _tokenId) external whenNotPaused {
var group = tokenIndexToGroup[_tokenId];
require(group.addressToContribution[msg.sender] > 0 ||
msg.sender == ceoAddress ||
msg.sender == cooAddress1 ||
msg.sender == cooAddress2 ||
msg.sender == cooAddress3 ||
msg.sender == cfoAddress);
// Safety check that enough money has been contributed to group
var price = linkedContract.priceOf(_tokenId);
require(group.contributedBalance >= price);
// Safety check that token had not be purchased yet
require(group.purchasePrice == 0);
_purchase(_tokenId, price);
}
/// @notice Allow user to contribute to _tokenId token group
/// @param _tokenId The ID of the token group to be joined
function contributeToTokenGroup(uint256 _tokenId)
external payable whenNotForking whenNotPaused {
address userAdd = msg.sender;
// Safety check to prevent against an un expected 0x0 default.
require(_addressNotNull(userAdd));
/// Safety check to make sure contributor has not already joined this group
var group = tokenIndexToGroup[_tokenId];
var contributor = userAddressToContributor[userAdd];
if (!group.exists) { // Create group if not exists
group.exists = true;
activeGroups += 1;
} else {
require(group.addressToContributorArrIndex[userAdd] == 0);
}
if (!contributor.exists) { // Create contributor if not exists
userAddressToContributor[userAdd].exists = true;
} else {
require(contributor.tokenIdToGroupArrIndex[_tokenId] == 0);
}
// Safety check to make sure group isn't currently holding onto token
// or has a group record stored (for sales proceeds distribution)
require(group.purchasePrice == 0);
/// Safety check to ensure amount contributed is higher than min required percentage
/// of purchase price
uint256 tokenPrice = linkedContract.priceOf(_tokenId);
require(msg.value >= uint256(SafeMath.div(tokenPrice, MAX_CONTRIBUTION_SLOTS)));
// Index saved is 1 + the array's index, b/c 0 is the default value in a mapping,
// so as stored on the mapping, array index will begin at 1
uint256 cIndex = tokenIndexToGroup[_tokenId].contributorArr.push(userAdd);
tokenIndexToGroup[_tokenId].addressToContributorArrIndex[userAdd] = cIndex;
uint256 amountNeeded = SafeMath.sub(tokenPrice, group.contributedBalance);
if (msg.value > amountNeeded) {
tokenIndexToGroup[_tokenId].addressToContribution[userAdd] = amountNeeded;
tokenIndexToGroup[_tokenId].contributedBalance += amountNeeded;
// refund excess paid
userAddressToContributor[userAdd].withdrawableBalance += SafeMath.sub(msg.value, amountNeeded);
FundsDeposited(userAdd, SafeMath.sub(msg.value, amountNeeded));
} else {
tokenIndexToGroup[_tokenId].addressToContribution[userAdd] = msg.value;
tokenIndexToGroup[_tokenId].contributedBalance += msg.value;
}
// Index saved is 1 + the array's index, b/c 0 is the default value in a mapping,
// so as stored on the mapping, array index will begin at 1
uint256 gIndex = userAddressToContributor[userAdd].groupArr.push(_tokenId);
userAddressToContributor[userAdd].tokenIdToGroupArrIndex[_tokenId] = gIndex;
JoinGroup(
_tokenId,
userAdd,
tokenIndexToGroup[_tokenId].contributedBalance,
tokenIndexToGroup[_tokenId].addressToContribution[userAdd]
);
// Purchase token if enough funds contributed
if (tokenIndexToGroup[_tokenId].contributedBalance >= tokenPrice) {
_purchase(_tokenId, tokenPrice);
}
}
/// @notice Allow user to leave purchase group; note that their contribution
/// will be added to their withdrawable balance, and not directly refunded.
/// User can call withdrawBalance to retrieve funds.
/// @param _tokenId The ID of the Token purchase group to be left
function leaveTokenGroup(uint256 _tokenId) external whenNotPaused {
address userAdd = msg.sender;
var group = tokenIndexToGroup[_tokenId];
var contributor = userAddressToContributor[userAdd];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(userAdd));
// Safety check to make sure group exists;
require(group.exists);
// Safety check to make sure group hasn't purchased token already
require(group.purchasePrice == 0);
// Safety checks to ensure contributor has contributed to group
require(group.addressToContributorArrIndex[userAdd] > 0);
require(contributor.tokenIdToGroupArrIndex[_tokenId] > 0);
uint refundBalance = _clearContributorRecordInGroup(_tokenId, userAdd);
_clearGroupRecordInContributor(_tokenId, userAdd);
userAddressToContributor[userAdd].withdrawableBalance += refundBalance;
FundsDeposited(userAdd, refundBalance);
LeaveGroup(
_tokenId,
userAdd,
tokenIndexToGroup[_tokenId].contributedBalance,
refundBalance
);
}
/// @notice Allow user to leave purchase group; note that their contribution
/// and any funds they have in their withdrawableBalance will transfered to them.
/// @param _tokenId The ID of the Token purchase group to be left
function leaveTokenGroupAndWithdrawBalance(uint256 _tokenId) external whenNotPaused {
address userAdd = msg.sender;
var group = tokenIndexToGroup[_tokenId];
var contributor = userAddressToContributor[userAdd];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(userAdd));
// Safety check to make sure group exists;
require(group.exists);
// Safety check to make sure group hasn't purchased token already
require(group.purchasePrice == 0);
// Safety checks to ensure contributor has contributed to group
require(group.addressToContributorArrIndex[userAdd] > 0);
require(contributor.tokenIdToGroupArrIndex[_tokenId] > 0);
uint refundBalance = _clearContributorRecordInGroup(_tokenId, userAdd);
_clearGroupRecordInContributor(_tokenId, userAdd);
userAddressToContributor[userAdd].withdrawableBalance += refundBalance;
FundsDeposited(userAdd, refundBalance);
_withdrawUserFunds(userAdd);
LeaveGroup(
_tokenId,
userAdd,
tokenIndexToGroup[_tokenId].contributedBalance,
refundBalance
);
}
/// @dev Withdraw balance from own account
function withdrawBalance() external whenNotPaused {
require(_addressNotNull(msg.sender));
require(userAddressToContributor[msg.sender].exists);
_withdrawUserFunds(msg.sender);
}
/** Admin Fns **/
/// @notice Fn for adjusting commission rate
/// @param numerator Numerator for calculating funds distributed
/// @param denominator Denominator for calculating funds distributed
function adjustCommission(uint256 numerator, uint256 denominator) external onlyCLevel {
require(numerator <= denominator);
distributionNumerator = numerator;
distributionDenominator = denominator;
}
/// @dev In the event of needing a fork, this function moves all
/// of a group's contributors' contributions into their withdrawable balance.
/// @notice Group is dissolved after fn call
/// @param _tokenId The ID of the Token purchase group
function dissolveTokenGroup(uint256 _tokenId) external onlyCOO whenForking {
var group = tokenIndexToGroup[_tokenId];
// Safety check to make sure group exists and had not purchased a token
require(group.exists);
require(group.purchasePrice == 0);
for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) {
address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i];
var userContribution = group.addressToContribution[userAdd];
_clearGroupRecordInContributor(_tokenId, userAdd);
// clear contributor record on group
tokenIndexToGroup[_tokenId].addressToContribution[userAdd] = 0;
tokenIndexToGroup[_tokenId].addressToContributorArrIndex[userAdd] = 0;
// move contributor's contribution to their withdrawable balance
userAddressToContributor[userAdd].withdrawableBalance += userContribution;
ProceedsDeposited(_tokenId, userAdd, userContribution);
}
activeGroups -= 1;
tokenIndexToGroup[_tokenId].exists = false;
}
/// @dev Backup fn to allow distribution of funds after sale,
/// for the special scenario where an alternate sale platform is used;
/// @notice Group is dissolved after fn call
/// @param _tokenId The ID of the Token purchase group
/// @param _amount Funds to be distributed
function distributeCustomSaleProceeds(uint256 _tokenId, uint256 _amount) external onlyCOO {
var group = tokenIndexToGroup[_tokenId];
// Safety check to make sure group exists and had purchased the token
require(group.exists);
require(group.purchasePrice > 0);
require(_amount > 0);
_distributeProceeds(_tokenId, _amount);
}
/* /// @dev Allow distribution of interest payment,
/// Group is intact after fn call
/// @param _tokenId The ID of the Token purchase group
function distributeInterest(uint256 _tokenId) external onlyCOO payable {
var group = tokenIndexToGroup[_tokenId];
var amount = msg.value;
var excess = amount;
// Safety check to make sure group exists and had purchased the token
require(group.exists);
require(group.purchasePrice > 0);
require(amount > 0);
for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) {
address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i];
// calculate contributor's interest proceeds and add to their withdrawable balance
uint256 userProceeds = uint256(SafeMath.div(SafeMath.mul(amount,
tokenIndexToGroup[_tokenId].addressToContribution[userAdd]),
tokenIndexToGroup[_tokenId].contributedBalance));
userAddressToContributor[userAdd].withdrawableBalance += userProceeds;
excess -= userProceeds;
InterestDeposited(_tokenId, userAdd, userProceeds);
}
commissionBalance += excess;
Commission(_tokenId, excess);
} */
/// @dev Distribute funds after a token is sold.
/// Group is dissolved after fn call
/// @param _tokenId The ID of the Token purchase group
function distributeSaleProceeds(uint256 _tokenId) external onlyCOO {
var group = tokenIndexToGroup[_tokenId];
// Safety check to make sure group exists and had purchased the token
require(group.exists);
require(group.purchasePrice > 0);
// Safety check to make sure token had been sold
uint256 currPrice = linkedContract.priceOf(_tokenId);
uint256 soldPrice = _newPrice(group.purchasePrice);
require(currPrice > soldPrice);
uint256 paymentIntoContract = uint256(SafeMath.div(SafeMath.mul(soldPrice, 94), 100));
_distributeProceeds(_tokenId, paymentIntoContract);
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
function unpause() external onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
/// @dev Called by any "C-level" role to set the contract to . Used only when
/// a bug or exploit is detected and we need to limit damage.
function setToForking() external onlyCLevel whenNotForking {
forking = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
function setToNotForking() external onlyCEO whenForking {
// can't unpause if contract was upgraded
forking = false;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO1. Only available to the current CEO.
/// @param _newCOO1 The address of the new COO1
function setCOO1(address _newCOO1) external onlyCEO {
require(_newCOO1 != address(0));
cooAddress1 = _newCOO1;
}
/// @dev Assigns a new address to act as the COO2. Only available to the current CEO.
/// @param _newCOO2 The address of the new COO2
function setCOO2(address _newCOO2) external onlyCEO {
require(_newCOO2 != address(0));
cooAddress2 = _newCOO2;
}
/// @dev Assigns a new address to act as the COO3. Only available to the current CEO.
/// @param _newCOO3 The address of the new COO3
function setCOO3(address _newCOO3) external onlyCEO {
require(_newCOO3 != address(0));
cooAddress3 = _newCOO3;
}
/// @dev Backup fn to allow transfer of token out of
/// contract, for use where a purchase group wants to use an alternate
/// selling platform
/// @param _tokenId The ID of the Token purchase group
/// @param _to Address to transfer token to
function transferToken(uint256 _tokenId, address _to) external onlyCOO {
var group = tokenIndexToGroup[_tokenId];
// Safety check to make sure group exists and had purchased the token
require(group.exists);
require(group.purchasePrice > 0);
linkedContract.transfer(_to, _tokenId);
}
/// @dev Withdraws sale commission, CFO-only functionality
/// @param _to Address for commission to be sent to
function withdrawCommission(address _to) external onlyCFO {
uint256 balance = commissionBalance;
address transferee = (_to == address(0)) ? cfoAddress : _to;
commissionBalance = 0;
if (balance > 0) {
transferee.transfer(balance);
}
FundsWithdrawn(transferee, balance);
}
/** Information Query Fns **/
/// @dev Get contributed balance in _tokenId token group for user
/// @param _tokenId The ID of the token to be queried
function getContributionBalanceForTokenGroup(uint256 _tokenId, address userAdd) external view returns (uint balance) {
var group = tokenIndexToGroup[_tokenId];
require(group.exists);
balance = group.addressToContribution[userAdd];
}
/// @dev Get contributed balance in _tokenId token group for user
/// @param _tokenId The ID of the token to be queried
function getSelfContributionBalanceForTokenGroup(uint256 _tokenId) external view returns (uint balance) {
var group = tokenIndexToGroup[_tokenId];
require(group.exists);
balance = group.addressToContribution[msg.sender];
}
/// @dev Get array of contributors' addresses in _tokenId token group
/// @param _tokenId The ID of the token to be queried
function getContributorsInTokenGroup(uint256 _tokenId) external view returns (address[] contribAddr) {
var group = tokenIndexToGroup[_tokenId];
require(group.exists);
contribAddr = group.contributorArr;
}
/// @dev Get no. of contributors in _tokenId token group
/// @param _tokenId The ID of the token to be queried
function getContributorsInTokenGroupCount(uint256 _tokenId) external view returns (uint count) {
var group = tokenIndexToGroup[_tokenId];
require(group.exists);
count = group.contributorArr.length;
}
/// @dev Get list of tokenIds of token groups a user contributed to
function getGroupsContributedTo(address userAdd) external view returns (uint256[] groupIds) {
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(userAdd));
var contributor = userAddressToContributor[userAdd];
require(contributor.exists);
groupIds = contributor.groupArr;
}
/// @dev Get list of tokenIds of token groups the user contributed to
function getSelfGroupsContributedTo() external view returns (uint256[] groupIds) {
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(msg.sender));
var contributor = userAddressToContributor[msg.sender];
require(contributor.exists);
groupIds = contributor.groupArr;
}
/// @dev Get price at which token group purchased _tokenId token
function getGroupPurchasedPrice(uint256 _tokenId) external view returns (uint256 price) {
var group = tokenIndexToGroup[_tokenId];
require(group.exists);
require(group.purchasePrice > 0);
price = group.purchasePrice;
}
/// @dev Get withdrawable balance from sale proceeds for a user
function getWithdrawableBalance() external view returns (uint256 balance) {
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(msg.sender));
var contributor = userAddressToContributor[msg.sender];
require(contributor.exists);
balance = contributor.withdrawableBalance;
}
/// @dev Get total contributed balance in _tokenId token group
/// @param _tokenId The ID of the token group to be queried
function getTokenGroupTotalBalance(uint256 _tokenId) external view returns (uint balance) {
var group = tokenIndexToGroup[_tokenId];
require(group.exists);
balance = group.contributedBalance;
}
/*** PRIVATE FUNCTIONS ***/
/// @dev Safety check on _to address to prevent against an unexpected 0x0 default.
/// @param _to Address to be checked
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
/// @dev Clears record of a Contributor from a Group's record
/// @param _tokenId Token ID of Group to be cleared
/// @param _userAdd Address of Contributor
function _clearContributorRecordInGroup(uint256 _tokenId, address _userAdd) private returns (uint256 refundBalance) {
var group = tokenIndexToGroup[_tokenId];
// Index was saved is 1 + the array's index, b/c 0 is the default value
// in a mapping.
uint cIndex = group.addressToContributorArrIndex[_userAdd] - 1;
uint lastCIndex = group.contributorArr.length - 1;
refundBalance = group.addressToContribution[_userAdd];
// clear contribution record in group
tokenIndexToGroup[_tokenId].addressToContributorArrIndex[_userAdd] = 0;
tokenIndexToGroup[_tokenId].addressToContribution[_userAdd] = 0;
// move address in last position to deleted contributor's spot
if (lastCIndex > 0) {
tokenIndexToGroup[_tokenId].addressToContributorArrIndex[group.contributorArr[lastCIndex]] = cIndex;
tokenIndexToGroup[_tokenId].contributorArr[cIndex] = group.contributorArr[lastCIndex];
}
tokenIndexToGroup[_tokenId].contributorArr.length -= 1;
tokenIndexToGroup[_tokenId].contributedBalance -= refundBalance;
}
/// @dev Clears record of a Group from a Contributor's record
/// @param _tokenId Token ID of Group to be cleared
/// @param _userAdd Address of Contributor
function _clearGroupRecordInContributor(uint256 _tokenId, address _userAdd) private {
// Index saved is 1 + the array's index, b/c 0 is the default value
// in a mapping.
uint gIndex = userAddressToContributor[_userAdd].tokenIdToGroupArrIndex[_tokenId] - 1;
uint lastGIndex = userAddressToContributor[_userAdd].groupArr.length - 1;
// clear Group record in Contributor
userAddressToContributor[_userAdd].tokenIdToGroupArrIndex[_tokenId] = 0;
// move tokenId from end of array to deleted Group record's spot
if (lastGIndex > 0) {
userAddressToContributor[_userAdd].tokenIdToGroupArrIndex[userAddressToContributor[_userAdd].groupArr[lastGIndex]] = gIndex;
userAddressToContributor[_userAdd].groupArr[gIndex] = userAddressToContributor[_userAdd].groupArr[lastGIndex];
}
userAddressToContributor[_userAdd].groupArr.length -= 1;
}
/// @dev Redistribute proceeds from token purchase
/// @param _tokenId Token ID of token to be purchased
/// @param _amount Amount paid into contract for token
function _distributeProceeds(uint256 _tokenId, uint256 _amount) private {
uint256 fundsForDistribution = uint256(SafeMath.div(SafeMath.mul(_amount,
distributionNumerator), distributionDenominator));
uint256 commission = _amount;
for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) {
address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i];
// calculate contributor's sale proceeds and add to their withdrawable balance
uint256 userProceeds = uint256(SafeMath.div(SafeMath.mul(fundsForDistribution,
tokenIndexToGroup[_tokenId].addressToContribution[userAdd]),
tokenIndexToGroup[_tokenId].contributedBalance));
_clearGroupRecordInContributor(_tokenId, userAdd);
// clear contributor record on group
tokenIndexToGroup[_tokenId].addressToContribution[userAdd] = 0;
tokenIndexToGroup[_tokenId].addressToContributorArrIndex[userAdd] = 0;
commission -= userProceeds;
userAddressToContributor[userAdd].withdrawableBalance += userProceeds;
ProceedsDeposited(_tokenId, userAdd, userProceeds);
}
commissionBalance += commission;
Commission(_tokenId, commission);
activeGroups -= 1;
tokenIndexToGroup[_tokenId].exists = false;
tokenIndexToGroup[_tokenId].contributorArr.length = 0;
tokenIndexToGroup[_tokenId].contributedBalance = 0;
tokenIndexToGroup[_tokenId].purchasePrice = 0;
}
/// @dev Calculates next price of celebrity token
/// @param _oldPrice Previous price
function _newPrice(uint256 _oldPrice) private view returns (uint256 newPrice) {
if (_oldPrice < firstStepLimit) {
// first stage
newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 200), 94);
} else if (_oldPrice < secondStepLimit) {
// second stage
newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 120), 94);
} else {
// third stage
newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 115), 94);
}
}
/// @dev Calls CelebrityToken purchase fn and updates records
/// @param _tokenId Token ID of token to be purchased
/// @param _amount Amount to be paid to CelebrityToken
function _purchase(uint256 _tokenId, uint256 _amount) private {
tokenIndexToGroup[_tokenId].purchasePrice = _amount;
linkedContract.purchase.value(_amount)(_tokenId);
TokenPurchased(_tokenId, _amount);
}
function _withdrawUserFunds(address userAdd) private {
uint256 balance = userAddressToContributor[userAdd].withdrawableBalance;
userAddressToContributor[userAdd].withdrawableBalance = 0;
if (balance > 0) {
FundsWithdrawn(userAdd, balance);
userAdd.transfer(balance);
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
contract CelebrityToken is ERC721 {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new person comes into existence.
event Birth(uint256 tokenId, string name, address owner);
/// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
/// @dev Transfer event as defined in current draft of ERC721.
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoCelebrities"; // solhint-disable-line
string public constant SYMBOL = "CelebrityToken"; // solhint-disable-line
address public ceoAddress;
address public cooAddress;
uint256 public promoCreatedCount;
/*** DATATYPES ***/
struct Person {
string name;
}
/*** CONSTRUCTOR ***/
function CelebrityToken() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
) public;
/// For querying balance of a particular account
/// @param _owner The address for balance query
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns (uint256 balance);
/// @dev Creates a new promo Person with the given name, with given _price and assignes it to an address.
function createPromoPerson(address _owner, string _name, uint256 _price) public;
/// @dev Creates a new Person with the given name.
function createContractPerson(string _name) public;
/// @notice Returns all the relevant information about a specific person.
/// @param _tokenId The tokenId of the person of interest.
function getPerson(uint256 _tokenId) public view returns (
string personName,
uint256 sellingPrice,
address owner
);
function implementsERC721() public pure returns (bool);
/// @dev Required for ERC-721 compliance.
function name() public pure returns (string);
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address owner);
function payout(address _to) public;
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId) public payable;
function priceOf(uint256 _tokenId) public view returns (uint256 price);
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public;
/// @dev Assigns a new address to act as the COO. Only available to the current COO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public;
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns (string);
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _tokenId) public;
/// @param _owner The owner whose celebrity tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Persons array looking for persons belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens);
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total);
/// Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
) public;
/// Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public;
/*** PRIVATE FUNCTIONS ***/
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool);
/// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool);
/// For creating Person
function _createPerson(string _name, address _owner, uint256 _price) private;
/// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool);
/// For paying out balance on contract
function _payout(address _to) private;
/// @dev Assigns ownership of a specific Person to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private;
}
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;
}
}
|
Assigns a new address to act as the CFO. Only available to the current CEO. _newCFO The address of the new CFO
|
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
| 12,786,752 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Community vote
* @notice An oracle for relevant decisions made by the community.
*/
contract CommunityVote is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => bool) doubleSpenderByWallet;
uint256 maxDriipNonce;
uint256 maxNullNonce;
bool dataAvailable;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
dataAvailable = true;
}
//
// Results functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the max driip nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxDriipNonce()
public
view
returns (uint256)
{
return maxDriipNonce;
}
/// @notice Get the max null settlement nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxNullNonce()
public
view
returns (uint256)
{
return maxNullNonce;
}
/// @notice Get the data availability status
/// @return true if data is available
function isDataAvailable()
public
view
returns (bool)
{
return dataAvailable;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title CommunityVotable
* @notice An ownable that has a community vote property
*/
contract CommunityVotable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
CommunityVote public communityVote;
bool public communityVoteFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote);
event FreezeCommunityVoteEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote)
public
onlyDeployer
notNullAddress(address(newCommunityVote))
notSameAddresses(address(newCommunityVote), address(communityVote))
{
require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]");
// Set new community vote
CommunityVote oldCommunityVote = communityVote;
communityVote = newCommunityVote;
// Emit event
emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
}
/// @notice Freeze the community vote from further updates
/// @dev This operation can not be undone
function freezeCommunityVote()
public
onlyDeployer
{
communityVoteFrozen = true;
// Emit event
emit FreezeCommunityVoteEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier communityVoteInitialized() {
require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that contains registered beneficiaries
*/
contract Benefactor is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Beneficiary[] public beneficiaries;
mapping(address => uint256) public beneficiaryIndexByAddress;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterBeneficiaryEvent(Beneficiary beneficiary);
event DeregisterBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] > 0)
return false;
beneficiaries.push(beneficiary);
beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;
// Emit event
emit RegisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] == 0)
return false;
uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;
if (idx < beneficiaries.length - 1) {
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
}
beneficiaries.length--;
beneficiaryIndexByAddress[_beneficiary] = 0;
// Emit event
emit DeregisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Gauge whether the given address is the one of a registered beneficiary
/// @param beneficiary Address of beneficiary
/// @return true if beneficiary is registered, else false
function isRegisteredBeneficiary(Beneficiary beneficiary)
public
view
returns (bool)
{
return beneficiaryIndexByAddress[address(beneficiary)] > 0;
}
/// @notice Get the count of registered beneficiaries
/// @return The count of registered beneficiaries
function registeredBeneficiariesCount()
public
view
returns (uint256)
{
return beneficiaries.length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
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;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBenefactor
* @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount
*/
contract AccrualBenefactor is Benefactor {
using SafeMathIntLib for int256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => int256) private _beneficiaryFractionMap;
int256 public totalBeneficiaryFraction;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction);
event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given accrual beneficiary for the entirety fraction
/// @param beneficiary Address of accrual beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER());
}
/// @notice Register the given accrual beneficiary for the given fraction
/// @param beneficiary Address of accrual beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]");
require(
totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),
"Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]"
);
if (!super.registerBeneficiary(beneficiary))
return false;
_beneficiaryFractionMap[address(beneficiary)] = fraction;
totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);
// Emit event
emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);
return true;
}
/// @notice Deregister the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
if (!super.deregisterBeneficiary(beneficiary))
return false;
address _beneficiary = address(beneficiary);
totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]);
_beneficiaryFractionMap[_beneficiary] = 0;
// Emit event
emit DeregisterAccrualBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Get the fraction of benefits that is granted the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary
/// @return The beneficiary's fraction
function beneficiaryFraction(AccrualBeneficiary beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[address(beneficiary)];
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueFund
* @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst
* accrual beneficiaries.
*/
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance periodAccrual;
CurrenciesLib.Currencies periodCurrencies;
FungibleBalanceLib.Balance aggregateAccrual;
CurrenciesLib.Currencies aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent();
event RegisterServiceEvent(address service);
event DeregisterServiceEvent(address service);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to stores of currencies
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount,
address currencyCt, uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [RevenueFund.sol:124]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to stores of currencies
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyOperator
{
require(
ConstantsLib.PARTS_PER() == totalBeneficiaryFraction,
"Total beneficiary fraction out of bounds [RevenueFund.sol:236]"
);
// Execute transfer
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
int256 remaining = periodAccrual.get(currency.ct, currency.id);
if (0 >= remaining)
continue;
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
if (beneficiaryFraction(beneficiary) > 0) {
int256 transferable = periodAccrual.get(currency.ct, currency.id)
.mul(beneficiaryFraction(beneficiary))
.div(ConstantsLib.PARTS_PER());
if (transferable > remaining)
transferable = remaining;
if (transferable > 0) {
// Transfer ETH to the beneficiary
if (currency.ct == address(0))
beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), "");
// Transfer token to the beneficiary
else {
TransferController controller = transferController(currency.ct, "");
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id
)
);
require(success, "Approval by controller failed [RevenueFund.sol:274]");
beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, "");
}
remaining = remaining.sub(transferable);
}
}
}
// Roll over remaining to next accrual period
periodAccrual.set(remaining, currency.ct, currency.id);
}
// Close accrual period of accrual beneficiaries
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
// Require that beneficiary fraction is strictly positive
if (0 >= beneficiaryFraction(beneficiary))
continue;
// Close accrual period
beneficiary.closeAccrualPeriod(currencies);
}
// Emit event
emit CloseAccrualPeriodEvent();
}
}
/**
* Strings Library
*
* In summary this is a simple library of string functions which make simple
* string operations less tedious in solidity.
*
* Please be aware these functions can be quite gas heavy so use them only when
* necessary not to clog the blockchain with expensive transactions.
*
* @author James Lockhart <[email protected]>
*/
library Strings {
/**
* Concat (High gas cost)
*
* Appends two strings together and returns a new value
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string which will be the concatenated
* prefix
* @param _value The value to be the concatenated suffix
* @return string The resulting string from combinging the base and value
*/
function concat(string memory _base, string memory _value)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length > 0);
string memory _tmpValue = new string(_baseBytes.length +
_valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for (i = 0; i < _baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for (i = 0; i < _valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function indexOf(string memory _base, string memory _value)
internal
pure
returns (int) {
return _indexOf(_base, _value, 0);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string starting
* from a defined offset
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @param _offset The starting point to start searching from which can start
* from 0, but must not exceed the length of the string
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function _indexOf(string memory _base, string memory _value, uint _offset)
internal
pure
returns (int) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for (uint i = _offset; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
/**
* Length
*
* Returns the length of the specified string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string to be measured
* @return uint The length of the passed string
*/
function length(string memory _base)
internal
pure
returns (uint) {
bytes memory _baseBytes = bytes(_base);
return _baseBytes.length;
}
/**
* Sub String
*
* Extracts the beginning part of a string based on the desired length
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @return string The extracted sub string
*/
function substring(string memory _base, int _length)
internal
pure
returns (string memory) {
return _substring(_base, _length, 0);
}
/**
* Sub String
*
* Extracts the part of a string based on the desired length and offset. The
* offset and length must not exceed the lenth of the base string.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @param _offset The starting point to extract the sub string from
* @return string The extracted sub string
*/
function _substring(string memory _base, int _length, int _offset)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
assert(uint(_offset + _length) <= _baseBytes.length);
string memory _tmp = new string(uint(_length));
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = uint(_offset); i < uint(_offset + _length); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
return string(_tmpBytes);
}
/**
* String Split (Very high gas cost)
*
* Splits a string into an array of strings based off the delimiter value.
* Please note this can be quite a gas expensive function due to the use of
* storage so only use if really required.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string value to be split.
* @param _value The delimiter to split the string on which must be a single
* character
* @return string[] An array of values split based off the delimiter, but
* do not container the delimiter.
*/
function split(string memory _base, string memory _value)
internal
pure
returns (string[] memory splitArr) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint _splitsCount = 1;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == -1)
break;
else {
_splitsCount++;
_offset = uint(_limit) + 1;
}
}
splitArr = new string[](_splitsCount);
_offset = 0;
_splitsCount = 0;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == - 1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit) - _offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
splitArr[_splitsCount++] = string(_tmpBytes);
}
return splitArr;
}
/**
* Compare To
*
* Compares the characters of two strings, to ensure that they have an
* identical footprint
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent
*/
function compareTo(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i]) {
return false;
}
}
return true;
}
/**
* Compare To Ignore Case (High gas cost)
*
* Compares the characters of two strings, converting them to the same case
* where applicable to alphabetic characters to distinguish if the values
* match.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent value
* discarding case
*/
function compareToIgnoreCase(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i] &&
_upper(_baseBytes[i]) != _upper(_valueBytes[i])) {
return false;
}
}
return true;
}
/**
* Upper
*
* Converts all the values of a string to their corresponding upper case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to upper case
* @return string
*/
function upper(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _upper(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Lower
*
* Converts all the values of a string to their corresponding lower case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to lower case
* @return string
*/
function lower(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _lower(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Upper
*
* Convert an alphabetic character to upper case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to upper case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a lower case otherwise returns the original value
*/
function _upper(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x61 && _b1 <= 0x7A) {
return bytes1(uint8(_b1) - 32);
}
return _b1;
}
/**
* Lower
*
* Convert an alphabetic character to lower case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to lower case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a upper case otherwise returns the original value
*/
function _lower(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x41 && _b1 <= 0x5A) {
return bytes1(uint8(_b1) + 32);
}
return _b1;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PartnerFund
* @notice Where partners’ fees are managed
*/
contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using Strings for string;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Partner {
bytes32 nameHash;
uint256 fee;
address wallet;
uint256 index;
bool operatorCanUpdate;
bool partnerCanUpdate;
FungibleBalanceLib.Balance active;
FungibleBalanceLib.Balance staged;
TxHistoryLib.TxHistory txHistory;
FullBalanceHistory[] fullBalanceHistory;
}
struct FullBalanceHistory {
uint256 listIndex;
int256 balance;
uint256 blockNumber;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Partner[] private partners;
mapping(bytes32 => uint256) private _indexByNameHash;
mapping(address => uint256) private _indexByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet);
event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet);
event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee);
event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee);
event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee);
event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee);
event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet);
event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet);
event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet);
event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet);
event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
_receiveEthersTo(
indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive ethers to
/// @param tag The tag of the concerned partner
function receiveEthersTo(address tag, string memory)
public
payable
{
_receiveEthersTo(
uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Receive tokens to
/// @param tag The tag of the concerned partner
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
uint256(tag) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Hash name
/// @param name The name to be hashed
/// @return The hash value
function hashName(string memory name)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(name.upper()));
}
/// @notice Get deposit by partner and deposit indices
/// @param partnerIndex The index of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByIndices(uint256 partnerIndex, uint256 depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Require partner index is one of registered partner
require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]");
return _depositByIndices(partnerIndex - 1, depositIndex);
}
/// @notice Get deposit by partner name and deposit indices
/// @param name The name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByName(string memory name, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name is registered
return _depositByIndices(indexByName(name) - 1, depositIndex);
}
/// @notice Get deposit by partner name hash and deposit indices
/// @param nameHash The hashed name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByNameHash(bytes32 nameHash, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name hash is registered
return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex);
}
/// @notice Get deposit by partner wallet and deposit indices
/// @param wallet The wallet of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByWallet(address wallet, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner wallet is registered
return _depositByIndices(indexByWallet(wallet) - 1, depositIndex);
}
/// @notice Get deposits count by partner index
/// @param index The index of the concerned partner
/// return The deposits count
function depositsCountByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]");
return _depositsCountByIndex(index - 1);
}
/// @notice Get deposits count by partner name
/// @param name The name of the concerned partner
/// return The deposits count
function depositsCountByName(string memory name)
public
view
returns (uint256)
{
// Implicitly require that partner name is registered
return _depositsCountByIndex(indexByName(name) - 1);
}
/// @notice Get deposits count by partner name hash
/// @param nameHash The hashed name of the concerned partner
/// return The deposits count
function depositsCountByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Implicitly require that partner name hash is registered
return _depositsCountByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get deposits count by partner wallet
/// @param wallet The wallet of the concerned partner
/// return The deposits count
function depositsCountByWallet(address wallet)
public
view
returns (uint256)
{
// Implicitly require that partner wallet is registered
return _depositsCountByIndex(indexByWallet(wallet) - 1);
}
/// @notice Get active balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]");
return _activeBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name hash is registered
return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]");
return _stagedBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get the number of partners
/// @return The number of partners
function partnersCount()
public
view
returns (uint256)
{
return partners.length;
}
/// @notice Register a partner by name
/// @param name The name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByName(string memory name, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Require not empty name string
require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]");
// Hash name
bytes32 nameHash = hashName(name);
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameEvent(name, fee, wallet);
}
/// @notice Register a partner by name hash
/// @param nameHash The hashed name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet);
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
uint256 index = _indexByNameHash[nameHash];
require(0 < index, "Some error message when require fails [PartnerFund.sol:431]");
return index;
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByName(string memory name)
public
view
returns (uint256)
{
return indexByNameHash(hashName(name));
}
/// @notice Gets the 1-based index of partner by its wallet
/// @dev Reverts if wallet does not correspond to registered partner
/// @return Index of partner by given wallet
function indexByWallet(address wallet)
public
view
returns (uint256)
{
uint256 index = _indexByWallet[wallet];
require(0 < index, "Some error message when require fails [PartnerFund.sol:455]");
return index;
}
/// @notice Gauge whether a partner by the given name is registered
/// @param name The name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByName(string memory name)
public
view
returns (bool)
{
return (0 < _indexByNameHash[hashName(name)]);
}
/// @notice Gauge whether a partner by the given name hash is registered
/// @param nameHash The hashed name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByNameHash(bytes32 nameHash)
public
view
returns (bool)
{
return (0 < _indexByNameHash[nameHash]);
}
/// @notice Gauge whether a partner by the given wallet is registered
/// @param wallet The wallet of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByWallet(address wallet)
public
view
returns (bool)
{
return (0 < _indexByWallet[wallet]);
}
/// @notice Get the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @return The fee fraction
function feeByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]");
return _partnerFeeByIndex(index - 1);
}
/// @notice Get the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @return The fee fraction
function feeByName(string memory name)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name is registered
return _partnerFeeByIndex(indexByName(name) - 1);
}
/// @notice Get the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The fee fraction
function feeByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name hash is registered
return _partnerFeeByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @return The fee fraction
function feeByWallet(address wallet)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner wallet is registered
return _partnerFeeByIndex(indexByWallet(wallet) - 1);
}
/// @notice Set the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByIndex(uint256 index, uint256 newFee)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]");
// Update fee
uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee);
// Emit event
emit SetFeeByIndexEvent(index, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByName(string memory name, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee);
// Emit event
emit SetFeeByNameEvent(name, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByNameHash(bytes32 nameHash, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name hash is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee);
// Emit event
emit SetFeeByNameHashEvent(nameHash, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByWallet(address wallet, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner wallet is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee);
// Emit event
emit SetFeeByWalletEvent(wallet, oldFee, newFee);
}
/// @notice Get the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return The wallet
function walletByIndex(uint256 index)
public
view
returns (address)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]");
return partners[index - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return The wallet
function walletByName(string memory name)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name is registered
return partners[indexByName(name) - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The wallet
function walletByNameHash(bytes32 nameHash)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name hash is registered
return partners[indexByNameHash(nameHash) - 1].wallet;
}
/// @notice Set the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByIndex(uint256 index, address newWallet)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]");
// Update wallet
address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet);
// Emit event
emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByName(string memory name, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByNameHash(bytes32 nameHash, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet);
}
/// @notice Set the new partner wallet by the given old partner wallet
/// @param oldWallet The old wallet of the concerned partner
/// @return newWallet The partner's new wallet
function setWalletByWallet(address oldWallet, address newWallet)
public
{
// Update wallet
_setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet);
// Emit event
emit SetPartnerWalletByWalletEvent(oldWallet, newWallet);
}
/// @notice Stage the amount for subsequent withdrawal
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stage(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId));
partners[index - 1].active.sub(amount, currencyCt, currencyId);
partners[index - 1].staged.add(amount, currencyCt, currencyId);
partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index - 1].fullBalanceHistory.push(
FullBalanceHistory(
partners[index - 1].txHistory.depositsCount() - 1,
partners[index - 1].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit StageEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @notice Withdraw the given amount from staged balance
/// @param amount The concerned amount to withdraw
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId));
partners[index - 1].staged.sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:754]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
/// @dev index is 0-based
function _receiveEthersTo(uint256 index, int256 amount)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]");
// Add to active
partners[index].active.add(amount, address(0), 0);
partners[index].txHistory.addDeposit(amount, address(0), 0);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(address(0), 0),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, address(0), 0);
}
/// @dev index is 0-based
function _receiveTokensTo(uint256 index, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]");
require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:805]");
// Add to active
partners[index].active.add(amount, currencyCt, currencyId);
partners[index].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @dev partnerIndex is 0-based
function _depositByIndices(uint256 partnerIndex, uint256 depositIndex)
private
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]");
FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex];
(,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex);
balance = entry.balance;
blockNumber = entry.blockNumber;
}
/// @dev index is 0-based
function _depositsCountByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fullBalanceHistory.length;
}
/// @dev index is 0-based
function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].active.get(currencyCt, currencyId);
}
/// @dev index is 0-based
function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].staged.get(currencyCt, currencyId);
}
function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
private
{
// Require that the name is not previously registered
require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]");
// Require possibility to update
require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]");
// Add new partner
partners.length++;
// Reference by 1-based index
uint256 index = partners.length;
// Update partner map
partners[index - 1].nameHash = nameHash;
partners[index - 1].fee = fee;
partners[index - 1].wallet = wallet;
partners[index - 1].partnerCanUpdate = partnerCanUpdate;
partners[index - 1].operatorCanUpdate = operatorCanUpdate;
partners[index - 1].index = index;
// Update name hash to index map
_indexByNameHash[nameHash] = index;
// Update wallet to index map
_indexByWallet[wallet] = index;
}
/// @dev index is 0-based
function _setPartnerFeeByIndex(uint256 index, uint256 fee)
private
returns (uint256)
{
uint256 oldFee = partners[index].fee;
// If operator tries to change verify that operator has access
if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]");
else {
// Require that msg.sender is partner
require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]");
}
// Update stored fee
partners[index].fee = fee;
return oldFee;
}
// @dev index is 0-based
function _setPartnerWalletByIndex(uint256 index, address newWallet)
private
returns (address)
{
address oldWallet = partners[index].wallet;
// If address has not been set operator is the only allowed to change it
if (oldWallet == address(0))
require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]");
// Else if operator tries to change verify that operator has access
else if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]");
else {
// Require that msg.sender is partner
require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]");
// Require that new wallet is not zero-address if it can not be changed by operator
require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]");
}
// Update stored wallet
partners[index].wallet = newWallet;
// Update address to tag map
if (oldWallet != address(0))
_indexByWallet[oldWallet] = 0;
if (newWallet != address(0))
_indexByWallet[newWallet] = index;
return oldWallet;
}
// @dev index is 0-based
function _partnerFeeByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fee;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementTypesLib
* @dev Types for driip settlements
*/
library DriipSettlementTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum SettlementRole {Origin, Target}
struct SettlementParty {
uint256 nonce;
address wallet;
bool done;
uint256 doneBlockNumber;
}
struct Settlement {
string settledKind;
bytes32 settledHash;
SettlementParty origin;
SettlementParty target;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementState
* @notice Where driip settlement state is managed
*/
contract DriipSettlementState is Ownable, Servable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INIT_SETTLEMENT_ACTION = "init_settlement";
string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done";
string constant public SET_MAX_NONCE_ACTION = "set_max_nonce";
string constant public SET_FEE_TOTAL_ACTION = "set_fee_total";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256 public maxDriipNonce;
DriipSettlementTypesLib.Settlement[] public settlements;
mapping(address => uint256[]) public walletSettlementIndices;
mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce;
mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap;
bool public upgradesFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole,
bool done, uint256 doneBlockNumber);
event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency,
uint256 maxNonce);
event SetMaxDriipNonceEvent(uint256 maxDriipNonce);
event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce);
event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee);
event FreezeUpgradesEvent();
event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the count of settlements
function settlementsCount()
public
view
returns (uint256)
{
return settlements.length;
}
/// @notice Get the count of settlements for given wallet
/// @param wallet The address for which to return settlement count
/// @return count of settlements for the provided wallet
function settlementsCountByWallet(address wallet)
public
view
returns (uint256)
{
return walletSettlementIndices[wallet].length;
}
/// @notice Get settlement of given wallet and index
/// @param wallet The address for which to return settlement
/// @param index The wallet's settlement index
/// @return settlement for the provided wallet and index
function settlementByWalletAndIndex(address wallet, uint256 index)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]");
return settlements[walletSettlementIndices[wallet][index] - 1];
}
/// @notice Get settlement of given wallet and wallet nonce
/// @param wallet The address for which to return settlement
/// @param nonce The wallet's nonce
/// @return settlement for the provided wallet and index
function settlementByWalletAndNonce(address wallet, uint256 nonce)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]");
return settlements[walletNonceSettlementIndex[wallet][nonce] - 1];
}
/// @notice Initialize settlement, i.e. create one if no such settlement exists
/// for the double pair of wallets and nonces
/// @param settledKind The kind of driip of the settlement
/// @param settledHash The hash of driip of the settlement
/// @param originWallet The address of the origin wallet
/// @param originNonce The wallet nonce of the origin wallet
/// @param targetWallet The address of the target wallet
/// @param targetNonce The wallet nonce of the target wallet
function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet,
uint256 originNonce, address targetWallet, uint256 targetNonce)
public
onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION)
{
if (
0 == walletNonceSettlementIndex[originWallet][originNonce] &&
0 == walletNonceSettlementIndex[targetWallet][targetNonce]
) {
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
// Emit event
emit InitSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
}
/// @notice Set the done of the given settlement role in the given settlement
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @param done The done flag
function completeSettlementParty(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole, bool done)
public
onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage party =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin :
settlements[index - 1].target;
// Update party done and done block number properties
party.done = done;
party.doneBlockNumber = done ? block.number : 0;
// Emit event
emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber);
}
/// @notice Gauge whether the settlement is done wrt the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Return done
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.done :
settlements[index - 1].target.done
);
}
/// @notice Gauge whether the settlement is done wrt the given wallet, nonce
/// and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]");
// Return done
return settlementParty.done;
}
/// @notice Get the done block number of the settlement party with the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]");
// Return done block number
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.doneBlockNumber :
settlements[index - 1].target.doneBlockNumber
);
}
/// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]");
// Return done block number
return settlementParty.doneBlockNumber;
}
/// @notice Set the max (driip) nonce
/// @param _maxDriipNonce The max nonce
function setMaxDriipNonce(uint256 _maxDriipNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
maxDriipNonce = _maxDriipNonce;
// Emit event
emit SetMaxDriipNonceEvent(maxDriipNonce);
}
/// @notice Update the max driip nonce property from CommunityVote contract
function updateMaxDriipNonceFromCommunityVote()
public
{
uint256 _maxDriipNonce = communityVote.getMaxDriipNonce();
if (0 == _maxDriipNonce)
return;
maxDriipNonce = _maxDriipNonce;
// Emit event
emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce);
}
/// @notice Get the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
return walletCurrencyMaxNonce[wallet][currency.ct][currency.id];
}
/// @notice Set the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @param maxNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency,
uint256 maxNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
// Update max nonce value
walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce;
// Emit event
emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce);
}
/// @notice Get the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param currency The concerned currency
/// @return The total fee
function totalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency)
public
view
returns (MonetaryTypesLib.NoncedAmount memory)
{
return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id];
}
/// @notice Set the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param _totalFee The total fee
function setTotalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee)
public
onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION)
{
// Update total fees value
totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee;
// Emit event
emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee);
}
/// @notice Freeze all future settlement upgrades
/// @dev This operation can not be undone
function freezeUpgrades()
public
onlyDeployer
{
// Freeze upgrade
upgradesFrozen = true;
// Emit event
emit FreezeUpgradesEvent();
}
/// @notice Upgrade settlement from other driip settlement state instance
function upgradeSettlement(string memory settledKind, bytes32 settledHash,
address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber,
address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber)
public
onlyDeployer
{
// Require that upgrades have not been frozen
require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]");
// Require that settlement has not been initialized/upgraded already
require(0 == walletNonceSettlementIndex[originWallet][originNonce], "Settlement exists for origin wallet and nonce [DriipSettlementState.sol:416]");
require(0 == walletNonceSettlementIndex[targetWallet][targetNonce], "Settlement exists for target wallet and nonce [DriipSettlementState.sol:417]");
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].origin.done = originDone;
settlements[index].origin.doneBlockNumber = originDoneBlockNumber;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
settlements[index].target.done = targetDone;
settlements[index].target.doneBlockNumber = targetDoneBlockNumber;
// Emit event
emit UpgradeSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
}
|
Internal functions -----------------------------------------------------------------------------------------------------------------
|
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
| 1,005,886 |
./full_match/80001/0xFDA64Bfd52fE2eEe38A4f5008d424A4b2297110d/sources/contracts/contract.sol
|
for registering a new address to be a shop address
|
function addShop(
string memory _name, string memory _email,
string memory _location,string memory _desp
) public returns (uint256) {
require(isShop[msg.sender]!=true && isClient[msg.sender]==false && msg.sender!=owner,"new-emp address only");
Shop storage shop = shops[shopAmount];
shop.title = _name;
shop.identity = msg.sender;
shop.emailOrPhone = _email;
shop.description=_desp;
shop.volumeTraded=0;
shop.joined = block.timestamp;
shopAmount++;
isShop[msg.sender]=true;
return shopAmount-1;
}
| 9,441,817 |
// SPDX-License-Identifier: GPLv3
pragma solidity ^0.6.12;
interface ERC20 {
function balanceOf(address who) external view returns (uint);
function decimals() external view returns (uint);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
}
interface ETHUSDT {
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external;
function transferFrom(address sender, address recipient, uint256 amount) external;
function decimals() external view returns (uint8);
}
contract Ownable {
address owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "only owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "address is null");
owner = newOwner;
}
}
contract BridgeTransfer is Ownable {
struct Transaction{
address token_address;
address from_address;
string to_address;
uint to_chain;
uint amount;
uint decimals;
uint time;
}
struct User{
Transaction[] trans;
}
mapping(address => User) users;
Transaction[] all_trans;
// 存入要转账的token
// token_address token的合约地址
// to_address 收款目标地址的字符串
// to_chain 收款目标链的编号
// amount 转账的金额
function deposit(address token_address, string memory to_address, uint to_chain, uint amount) public returns (bool){
require(token_address != address(0), "token_address is null");
require(amount > 0, "amount must great than zero");
uint decimals;
if (isUsdt(token_address)) {
ETHUSDT token = ETHUSDT(token_address);
token.transferFrom(msg.sender, address(this), amount);
decimals = token.decimals();
} else {
ERC20 token = ERC20(token_address);
bool result = token.transferFrom(msg.sender, address(this), amount);
require(result == true, "transferFrom fail");
decimals = token.decimals();
}
Transaction memory tran = Transaction(token_address, msg.sender, to_address, to_chain, amount, decimals, block.timestamp);
users[msg.sender].trans.push(tran);
all_trans.push(tran);
return true;
}
function deposit(string memory to_address, uint to_chain) public payable returns (bool){
require(msg.value > 0, "amount must great than zero");
Transaction memory tran = Transaction(address(0), msg.sender, to_address, to_chain, msg.value, 18, block.timestamp);
users[msg.sender].trans.push(tran);
all_trans.push(tran);
return true;
}
// 查询账户信息
// addr 账户的地址
function query_account(address addr)public view returns(uint, uint){
return (addr.balance, // 当前账户的BNB或TRX余额
users[addr].trans.length); // 当前账户总共有多少次跨链转账
}
// 查询token的余额和授权情况
// addr 要查询的地址
// token_address token的合约地址
function query_token(address addr, address token_address)public view returns(uint, uint){
if (isUsdt(token_address)) {
ETHUSDT token = ETHUSDT(token_address);
return (token.balanceOf(addr), // token的余额
token.allowance(addr, address(this))); // token的授权情况
} else {
ERC20 token = ERC20(token_address);
return (token.balanceOf(addr), // token的余额
token.allowance(addr, address(this))); // token的授权情况
}
}
// 查询用户指定编号的跨链转账详情
// addr 查询的用户地址
// index 查询转账的索引编号,不能大于等于query_account返回的总共跨链转账次数
function query_user_tran(address addr, uint index)public view returns(address, string memory, uint, uint, uint, uint){
require(index < users[addr].trans.length, "index out of bounds");
return (users[addr].trans[index].token_address, // token的合约地址
users[addr].trans[index].to_address, // 转账目标地址
users[addr].trans[index].to_chain, // 收款目标链的编号
users[addr].trans[index].amount, // 转账的金额
users[addr].trans[index].decimals, // 转账的金额小数位
users[addr].trans[index].time); // 转账发起时间(秒),unix timestamp
}
// 查询合约总共的跨链转账次数
function query_all_trans_length()public view returns(uint) {
return all_trans.length;
}
// 查询整个合约指定编号的跨链转账详情
// index 查询转账的索引编号,不能大于等于query_all_trans_length返回的总共跨链转账次数
function query_tran(uint index)public view returns(address, address, string memory, uint, uint, uint, uint) {
require(index < all_trans.length, "index out of bounds");
return (all_trans[index].token_address, // token的合约地址
all_trans[index].from_address, // 转账发起的用户地址
all_trans[index].to_address, // 转账目标地址
all_trans[index].to_chain, // 收款目标链的编号
all_trans[index].amount, // 转账的金额
all_trans[index].decimals, // 转账的金额小数位
all_trans[index].time); // 转账发起时间(秒),unix timestamp
}
function collect(address token_address, address collect_address, uint amount) public onlyOwner returns (bool){
require(token_address != address(0), "token_address is null");
require(collect_address != address(0), "collect_address is null");
require(amount > 0, "amount must great than zero");
if (isUsdt(token_address)) {
ETHUSDT token = ETHUSDT(token_address);
token.transfer(collect_address, amount);
} else {
ERC20 token = ERC20(token_address);
token.transfer(collect_address, amount);
}
return true;
}
function collect(address payable collect_address, uint amount) public onlyOwner returns (bool){
require(collect_address != address(0), "collect_address is null");
require(amount > 0, "amount must great than zero");
collect_address.transfer(amount);
return true;
}
function isUsdt(address addr) private pure returns (bool) {
return addr == address(0xdAC17F958D2ee523a2206206994597C13D831ec7) ? true : false;
}
}
|
查询用户指定编号的跨链转账详情 addr 查询的用户地址 index 查询转账的索引编号,不能大于等于query_account返回的总共跨链转账次数
|
function query_user_tran(address addr, uint index)public view returns(address, string memory, uint, uint, uint, uint){
require(index < users[addr].trans.length, "index out of bounds");
}
| 575,537 |
./partial_match/56/0x09cD7a706E6783b6Bea73240CEf9ae6fEFd06F70/sources/BiscuitMasterChef.sol
|
Deposit LP tokens to BiscuitFarmer.
|
function deposit(uint256 _pid, uint256 _amount, address _referrer) public {
require(_amount > 0, "BiscuitFarmer::deposit: amount must be greater than 0");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
_harvest(_pid);
uint256 feeForDep = 0;
if (pool.feeForDep > 0) {
feeForDep = _amount.mul(pool.feeForDep).div(1000);
pool.lpToken.safeTransferFrom(address(msg.sender), address(devaddr), feeForDep);
}
uint256 amount = _amount.sub(feeForDep);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), amount);
if (user.amount == 0) {
user.rewardDebtAtBlock = block.number;
}
user.amount = user.amount.add(amount);
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12);
if (referrers[address(msg.sender)] == address(0) && _referrer != address(0) && _referrer != address(msg.sender)) {
referrers[address(msg.sender)] = address(_referrer);
myReferrers[_referrer].push(msg.sender);
emit Referral(_referrer, msg.sender);
}
emit Deposit(msg.sender, _pid, _amount);
}
| 11,262,782 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IAsset
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// Part: IUniswapV2Router01
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @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;
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: IBalancerPool
interface IBalancerPool is IERC20 {
enum SwapKind {GIVEN_IN, GIVEN_OUT}
struct SwapRequest {
SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
function getPoolId() external view returns (bytes32 poolId);
function symbol() external view returns (string memory s);
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external view returns (uint256 amount);
}
// Part: IBalancerVault
interface IBalancerVault {
enum PoolSpecialization {GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN}
enum JoinKind {INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT}
enum ExitKind {EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT}
// enconding formats https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/balancer-js/src/pool-weighted/encoder.ts
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest calldata request
) external;
function getPool(bytes32 poolId) external view returns (address poolAddress, PoolSpecialization);
function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
function getPoolTokens(bytes32 poolId) external view returns (
IERC20[] calldata tokens,
uint256[] calldata balances,
uint256 lastChangeBlock
);
}
// Part: IUniswapV2Router02
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// Part: OpenZeppelin/[email protected]/ERC20
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: yearn/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: yearn/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IUniswapV2Router02 constant public uniswapRouter = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
IUniswapV2Router02 constant public sushiswapRouter = IUniswapV2Router02(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F));
IERC20 public constant weth = IERC20(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2));
IUniswapV2Router02 public router;
IBalancerVault public balancerVault;
IBalancerPool public bpt;
IERC20[] public rewardTokens;
IAsset[] public assets;
uint256[] public minAmountsOut;
bytes32 public balancerPoolId;
uint8 public numTokens;
uint8 public tokenIndex;
uint256 public constant max = type(uint256).max;
//1 0.01%
//5 0.05%
//10 0.1%
//50 0.5%
//100 1%
//1000 10%
//10000 100%
uint256 public maxSlippageIn; // bips
uint256 public maxSlippageOut; // bips
uint256 public maxSingleDeposit;
uint256 public minDepositPeriod; // seconds
uint256 public lastDepositTime;
uint256 public constant basisOne = 10000;
constructor(
address _vault,
address _balancerVault,
address _balancerPool,
uint256 _maxSlippageIn,
uint256 _maxSlippageOut,
uint256 _maxSingleDeposit,
uint256 _minDepositPeriod)
public BaseStrategy(_vault){
_initializeStrat(_vault, _balancerVault, _balancerPool, _maxSlippageIn, _maxSlippageOut, _maxSingleDeposit, _minDepositPeriod);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _balancerVault,
address _balancerPool,
uint256 _maxSlippageIn,
uint256 _maxSlippageOut,
uint256 _maxSingleDeposit,
uint256 _minDepositPeriod
) external {
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeStrat(_vault, _balancerVault, _balancerPool, _maxSlippageIn, _maxSlippageOut, _maxSingleDeposit, _minDepositPeriod);
}
function _initializeStrat(
address _vault,
address _balancerVault,
address _balancerPool,
uint256 _maxSlippageIn,
uint256 _maxSlippageOut,
uint256 _maxSingleDeposit,
uint256 _minDepositPeriod)
internal {
require(address(bpt) == address(0x0), "Strategy already initialized!");
bpt = IBalancerPool(_balancerPool);
balancerPoolId = bpt.getPoolId();
balancerVault = IBalancerVault(_balancerVault);
(address tokenAddress,) = balancerVault.getPool(balancerPoolId);
(IERC20[] memory tokens,,) = balancerVault.getPoolTokens(balancerPoolId);
numTokens = uint8(tokens.length);
assets = new IAsset[](numTokens);
tokenIndex = type(uint8).max;
for (uint8 i = 0; i < numTokens; i++) {
if (tokens[i] == want) {
tokenIndex = i;
}
assets[i] = IAsset(address(tokens[i]));
}
require(tokenIndex != type(uint8).max, "token not supported in pool!");
maxSlippageIn = _maxSlippageIn;
maxSlippageOut = _maxSlippageOut;
maxSingleDeposit = _maxSingleDeposit.mul(10 ** uint256(ERC20(address(want)).decimals()));
minAmountsOut = new uint256[](numTokens);
minDepositPeriod = _minDepositPeriod;
router = IUniswapV2Router02(uniswapRouter);
want.safeApprove(address(balancerVault), max);
}
event Cloned(address indexed clone);
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _balancerVault,
address _balancerPool,
uint256 _maxSlippageIn,
uint256 _maxSlippageOut,
uint256 _maxSingleDeposit,
uint256 _minDepositPeriod
) external returns (address payable newStrategy) {
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(
_vault, _strategist, _rewards, _keeper, _balancerVault, _balancerPool, _maxSlippageIn, _maxSlippageOut, _maxSingleDeposit, _minDepositPeriod
);
emit Cloned(newStrategy);
}
// ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************
function name() external view override returns (string memory) {
// Add your own name here, suggestion e.g. "StrategyCreamYFI"
return string(abi.encodePacked("SingleSidedBalancer ", bpt.symbol(), "Pool ", ERC20(address(want)).symbol()));
}
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(balanceOfPooled());
}
function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){
if (_debtOutstanding > 0) {
(_debtPayment, _loss) = liquidatePosition(_debtOutstanding);
}
uint256 beforeWant = balanceOfWant();
// 2 forms of profit. Incentivized rewards (BAL+other) and pool fees (want)
collectTradingFees();
sellRewards();
uint256 afterWant = balanceOfWant();
_profit = afterWant.sub(beforeWant);
if (_profit > _loss) {
_profit = _profit.sub(_loss);
_loss = 0;
} else {
_loss = _loss.sub(_profit);
_profit = 0;
}
}
event Debug(string name, uint256 value);
event Debug(string name, bytes value);
function adjustPosition(uint256 _debtOutstanding) internal override {
if (now - lastDepositTime < minDepositPeriod) {
return;
}
uint256 pooledBefore = balanceOfPooled();
uint256[] memory maxAmountsIn = new uint256[](numTokens);
uint256 amountIn = Math.min(maxSingleDeposit, balanceOfWant());
maxAmountsIn[tokenIndex] = amountIn;
if (maxAmountsIn[tokenIndex] > 0) {
uint256[] memory amountsIn = new uint256[](numTokens);
amountsIn[tokenIndex] = amountIn;
bytes memory userData = abi.encode(IBalancerVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, amountsIn, 0);
IBalancerVault.JoinPoolRequest memory request = IBalancerVault.JoinPoolRequest(assets, maxAmountsIn, userData, false);
balancerVault.joinPool(balancerPoolId, address(this), address(this), request);
uint256 pooledDelta = balanceOfPooled().sub(pooledBefore);
uint256 joinSlipped = amountIn > pooledDelta ? amountIn.sub(pooledDelta) : 0;
uint256 maxLoss = amountIn.mul(maxSlippageIn).div(basisOne);
require(joinSlipped <= maxLoss, "Exceeded maxSlippageIn!");
lastDepositTime = now;
}
}
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss){
if (estimatedTotalAssets() < _amountNeeded) {
_liquidatedAmount = liquidateAllPositions();
return (_liquidatedAmount, _amountNeeded.sub(_liquidatedAmount));
}
uint256 looseAmount = balanceOfWant();
if (_amountNeeded > looseAmount) {
uint256 toExitAmount = _amountNeeded.sub(looseAmount);
_sellBptForExactToken(toExitAmount);
_liquidatedAmount = Math.min(balanceOfWant(), _amountNeeded);
_loss = _amountNeeded.sub(_liquidatedAmount);
// enforce that amount exited didn't slip beyond our tolerance
uint256 exitedAmount = _liquidatedAmount.sub(looseAmount);
// just in case there's positive slippage
uint256 exitSlipped = toExitAmount > exitedAmount ? toExitAmount.sub(exitedAmount) : 0;
uint256 maxLoss = toExitAmount.mul(maxSlippageIn).div(basisOne);
require(exitSlipped <= maxLoss, "Exceeded maxSlippageOut!");
} else {
_liquidatedAmount = _amountNeeded;
}
}
function liquidateAllPositions() internal override returns (uint256 liquidated) {
uint256 bpts = balanceOfBpt();
if (bpts > 0) {
// exit entire position for single token. Could revert due to single exit limit enforced by balancer
bytes memory userData = abi.encode(IBalancerVault.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, bpts, tokenIndex);
IBalancerVault.ExitPoolRequest memory request = IBalancerVault.ExitPoolRequest(assets, minAmountsOut, userData, false);
balancerVault.exitPool(balancerPoolId, address(this), address(this), request);
}
return balanceOfWant();
}
function prepareMigration(address _newStrategy) internal override {
bpt.transfer(_newStrategy, balanceOfBpt());
for (uint i = 0; i < rewardTokens.length; i++) {
IERC20 token = rewardTokens[i];
uint256 balance = token.balanceOf(address(this));
if (balance > 0) {
token.transfer(_newStrategy, balance);
}
}
}
function protectedTokens() internal view override returns (address[] memory){}
function ethToWant(uint256 _amtInWei) public view override returns (uint256){
if (_amtInWei == 0) {
return 0;
}
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(want);
uint256[] memory amounts = router.getAmountsOut(_amtInWei, path);
return amounts[amounts.length - 1];
}
function tendTrigger(uint256 callCostInWei) public view override returns (bool) {
return now.sub(lastDepositTime) > minDepositPeriod && balanceOfWant() > 0;
}
function harvestTrigger(uint256 callCostInWei) public view override returns (bool){
bool hasRewards;
for (uint8 i = 0; i < rewardTokens.length; i++) {
ERC20 rewardToken = ERC20(address(rewardTokens[i]));
uint256 amount = rewardToken.balanceOf(address(this));
uint decReward = rewardToken.decimals();
uint decWant = ERC20(address(want)).decimals();
uint decDiff = decReward > decWant ? decReward.sub(decWant) : 0;
if (amount > 10 ** decDiff) {
hasRewards = true;
break;
}
}
return super.harvestTrigger(callCostInWei) && hasRewards;
}
// HELPERS //
function sellRewards() internal {
for (uint8 i = 0; i < rewardTokens.length; i++) {
ERC20 rewardToken = ERC20(address(rewardTokens[i]));
uint256 amount = rewardToken.balanceOf(address(this));
uint decReward = rewardToken.decimals();
uint decWant = ERC20(address(want)).decimals();
uint decDiff = decReward > decWant ? decReward.sub(decWant) : 0;
if (amount > 10 ** decDiff) {
bool isWeth = want == weth || address(rewardToken) == address(weth);
address[] memory path = new address[](isWeth ? 2 : 3);
path[0] = address(rewardToken);
if (isWeth) {
path[1] = address(want);
} else {
path[1] = address(weth);
path[2] = address(want);
}
router.swapExactTokensForTokens(amount, 0, path, address(this), now);
}
}
}
function collectTradingFees() internal {
uint256 total = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
uint256 profit = total.sub(debt);
_sellBptForExactToken(profit);
}
}
function balanceOfWant() public view returns (uint256 _amount){
return want.balanceOf(address(this));
}
function balanceOfBpt() public view returns (uint256 _amount){
return bpt.balanceOf(address(this));
}
function balanceOfReward(uint256 index) public view returns (uint256 _amount){
return rewardTokens[index].balanceOf(address(this));
}
function balanceOfPooled() public view returns (uint256 _amount){
uint256 totalWantPooled;
(IERC20[] memory tokens,uint256[] memory totalBalances,uint256 lastChangeBlock) = balancerVault.getPoolTokens(balancerPoolId);
for (uint8 i = 0; i < numTokens; i++) {
uint256 tokenPooled = totalBalances[i].mul(balanceOfBpt()).div(bpt.totalSupply());
if (tokenPooled > 0) {
IERC20 token = tokens[i];
if (token != want) {
IBalancerPool.SwapRequest memory request = _getSwapRequest(token, tokenPooled, lastChangeBlock);
// now denomated in want
tokenPooled = bpt.onSwap(request, totalBalances, i, tokenIndex);
}
totalWantPooled += tokenPooled;
}
}
return totalWantPooled;
}
function _getSwapRequest(IERC20 token, uint256 amount, uint256 lastChangeBlock) public view returns (IBalancerPool.SwapRequest memory request){
return IBalancerPool.SwapRequest(IBalancerPool.SwapKind.GIVEN_IN,
token,
want,
amount,
balancerPoolId,
lastChangeBlock,
address(this),
address(this),
abi.encode(0)
);
}
function _sellBptForExactToken(uint256 _amountTokenOut) internal {
uint256[] memory amountsOut = new uint256[](numTokens);
amountsOut[tokenIndex] = _amountTokenOut;
bytes memory userData = abi.encode(IBalancerVault.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT, amountsOut, balanceOfBpt());
IBalancerVault.ExitPoolRequest memory request = IBalancerVault.ExitPoolRequest(assets, minAmountsOut, userData, false);
balancerVault.exitPool(balancerPoolId, address(this), address(this), request);
}
// for partnership rewards like Lido or airdrops
function whitelistRewards(address _rewardToken) public onlyAuthorized {
IERC20 token = IERC20(_rewardToken);
token.approve(address(uniswapRouter), max);
token.approve(address(sushiswapRouter), max);
rewardTokens.push(token);
}
function delistAllRewards() public onlyAuthorized {
for (uint i = 0; i < rewardTokens.length; i++) {
rewardTokens[i].approve(address(uniswapRouter), 0);
rewardTokens[i].approve(address(sushiswapRouter), 0);
}
IERC20[] memory noRewardTokens;
rewardTokens = noRewardTokens;
}
function numRewards() public view returns (uint256 _num){
return rewardTokens.length;
}
function setParams(uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod) public onlyAuthorized {
require(_maxSlippageIn <= basisOne, "maxSlippageIn too high");
maxSlippageIn = _maxSlippageIn;
require(_maxSlippageOut <= basisOne, "maxSlippageOut too high");
maxSlippageOut = _maxSlippageOut;
maxSingleDeposit = _maxSingleDeposit;
minDepositPeriod = _minDepositPeriod;
}
function switchDex(bool isUniswap) external onlyAuthorized {
if (isUniswap) router = uniswapRouter;
else router = sushiswapRouter;
}
receive() external payable {}
}
|
Part: IBalancerVault enconding formats https:github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/balancer-js/src/pool-weighted/encoder.ts
|
interface IBalancerVault {
enum PoolSpecialization {GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN}
enum JoinKind {INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT}
enum ExitKind {EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT}
function getPoolId() external view returns (bytes32 poolId);
function symbol() external view returns (string memory s);
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external view returns (uint256 amount);
}
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
}
| 583,148 |
/**
*Submitted for verification at Etherscan.io on 2022-02-14
*/
pragma solidity 0.6.7;
abstract contract Setter {
function modifyParameters(bytes32, uint256) public virtual;
function addManualSetter(address) public virtual;
function removeManualSetter(address) public virtual;
function updateResult(uint256) public virtual;
function addAuthorization(address) public virtual;
function removeAuthorization(address) public virtual;
}
contract Proposal {
// addresses
address public constant GEB_DEBT_AUCTION_INITIAL_PARAM_SETTER = 0x7df2d51e69aA58B69C3dF18D75b8e9ACc3C1B04E;
address public constant GEB_DEBT_FLOOR_ADJUSTER = 0x0262Bd031B99c5fb99B47Dc4bEa691052f671447;
address public constant GEB_PAUSE_PROXY = 0xa57A4e6170930ac547C147CdF26aE4682FA8262E;
address public constant GEB_GAS_PRICE_ORACLE = 0x3a3e9d4D1AfC6f9d7e0E9A4032a7ddBc1500D7a5;
address public constant GEB_SINGLE_CEILING_SETTER = 0x54999Ee378b339f405a4a8a1c2f7722CD25960fa;
address public constant GEB_ESM = 0xa33Ea2Ac39902d4A206D6A1F8D38c7330C80f094;
// contracts being replaced
address public constant NEW_GEB_ESM_THRESHOLD_SETTER = 0x5E79C6Db9a04039B593877B96f885374470eFB90;
address public constant OLD_GEB_ESM_THRESHOLD_SETTER = 0x93EBA2905a2293E5C367eF053B5c2c07dc401311;
function execute(bool) public {
// GEB_DEBT_AUCTION_INITIAL_PARAM_SETTER - Set update delay to 7 days (604800 seconds)
Setter(GEB_DEBT_AUCTION_INITIAL_PARAM_SETTER).modifyParameters("updateDelay", 604800);
// GEB_DEBT_FLOOR_ADJUSTER - Remove 0xfA5e4955a11902f849ECaddEf355Db69C2036de6 from manual setters and add pauseProxy
Setter(GEB_DEBT_FLOOR_ADJUSTER).addManualSetter(GEB_PAUSE_PROXY);
Setter(GEB_DEBT_FLOOR_ADJUSTER).removeManualSetter(0xfA5e4955a11902f849ECaddEf355Db69C2036de6);
// GEB_GAS_PRICE_ORACLE - Increase to 350 gwei
Setter(GEB_GAS_PRICE_ORACLE).updateResult(350e9);
// GEB_SINGLE_CEILING_SETTER - Remove pauseProxy from manual setters
Setter(GEB_SINGLE_CEILING_SETTER).removeManualSetter(GEB_PAUSE_PROXY);
// GEB_ESM_THRESHOLD_SETTER - Set supplyPercentageToBurn to 100 (10%) // need new contract, authing on the ESM, deauthing the old
Setter(GEB_ESM).addAuthorization(NEW_GEB_ESM_THRESHOLD_SETTER);
Setter(GEB_ESM).removeAuthorization(OLD_GEB_ESM_THRESHOLD_SETTER);
}
}
|
GEB_DEBT_AUCTION_INITIAL_PARAM_SETTER - Set update delay to 7 days (604800 seconds) GEB_DEBT_FLOOR_ADJUSTER - Remove 0xfA5e4955a11902f849ECaddEf355Db69C2036de6 from manual setters and add pauseProxy GEB_GAS_PRICE_ORACLE - Increase to 350 gwei GEB_SINGLE_CEILING_SETTER - Remove pauseProxy from manual setters GEB_ESM_THRESHOLD_SETTER - Set supplyPercentageToBurn to 100 (10%) need new contract, authing on the ESM, deauthing the old
|
function execute(bool) public {
Setter(GEB_DEBT_AUCTION_INITIAL_PARAM_SETTER).modifyParameters("updateDelay", 604800);
Setter(GEB_DEBT_FLOOR_ADJUSTER).addManualSetter(GEB_PAUSE_PROXY);
Setter(GEB_DEBT_FLOOR_ADJUSTER).removeManualSetter(0xfA5e4955a11902f849ECaddEf355Db69C2036de6);
Setter(GEB_GAS_PRICE_ORACLE).updateResult(350e9);
Setter(GEB_SINGLE_CEILING_SETTER).removeManualSetter(GEB_PAUSE_PROXY);
Setter(GEB_ESM).addAuthorization(NEW_GEB_ESM_THRESHOLD_SETTER);
Setter(GEB_ESM).removeAuthorization(OLD_GEB_ESM_THRESHOLD_SETTER);
}
| 10,676,016 |
./full_match/77/0x48BeC2C1D4423504ac377107c2c68bEe347B30E1/sources/contracts/Asset.sol
|
Withdraws funds dst Asset destination address (balance owner) value Asset value
|
function exit(address dst, uint256 value) external onlyLive {
if (value > 2**255) {
revert UintOverflow();
}
ledger.add(msg.sender, address(asset), -int256(value));
if (!asset.transfer(dst, value)) {
revert TransferFiled(address(this), dst, address(asset), value);
}
emit Exit(dst, value);
}
uint256[50] private __gap;
| 5,046,826 |
./full_match/1/0x5577Cf81459b742Dbfe757f98cB3eD4eD8e7Df30/sources/contracts/RWAHubOffChainRedemptions.sol
|
To enable and disable off chain redemptions Minimum off chain redemption amount
|
{
bool public offChainRedemptionPaused;
uint256 public minimumOffChainRedemptionAmount;
constructor(
address _collateral,
address _rwa,
address managerAdmin,
address pauser,
address _assetSender,
address _feeRecipient,
uint256 _minimumDepositAmount,
uint256 _minimumRedemptionAmount
)
RWAHub(
_collateral,
_rwa,
managerAdmin,
pauser,
_assetSender,
_feeRecipient,
_minimumDepositAmount,
_minimumRedemptionAmount
)
{
minimumOffChainRedemptionAmount = _minimumRedemptionAmount;
}
function requestRedemptionServicedOffchain(
uint256 amountRWATokenToRedeem,
bytes32 offChainDestination
) external nonReentrant ifNotPaused(offChainRedemptionPaused) {
if (amountRWATokenToRedeem < minimumRedemptionAmount) {
revert RedemptionTooSmall();
}
bytes32 redemptionId = bytes32(redemptionRequestCounter++);
rwa.burnFrom(msg.sender, amountRWATokenToRedeem);
emit RedemptionRequestedServicedOffChain(
redemptionId,
msg.sender,
amountRWATokenToRedeem,
offChainDestination
);
}
function requestRedemptionServicedOffchain(
uint256 amountRWATokenToRedeem,
bytes32 offChainDestination
) external nonReentrant ifNotPaused(offChainRedemptionPaused) {
if (amountRWATokenToRedeem < minimumRedemptionAmount) {
revert RedemptionTooSmall();
}
bytes32 redemptionId = bytes32(redemptionRequestCounter++);
rwa.burnFrom(msg.sender, amountRWATokenToRedeem);
emit RedemptionRequestedServicedOffChain(
redemptionId,
msg.sender,
amountRWATokenToRedeem,
offChainDestination
);
}
function pauseOffChainRedemption() external onlyRole(PAUSER_ADMIN) {
offChainRedemptionPaused = true;
emit OffChainRedemptionPaused(msg.sender);
}
function unpauseOffChainRedemption() external onlyRole(MANAGER_ADMIN) {
offChainRedemptionPaused = false;
emit OffChainRedemptionUnpaused(msg.sender);
}
function setOffChainRedemptionMinimum(
uint256 _minimumOffChainRedemptionAmount
) external onlyRole(MANAGER_ADMIN) {
uint256 oldMinimum = minimumOffChainRedemptionAmount;
minimumOffChainRedemptionAmount = _minimumOffChainRedemptionAmount;
emit OffChainRedemptionMinimumSet(
oldMinimum,
_minimumOffChainRedemptionAmount
);
}
}
| 17,169,679 |
./partial_match/5/0xEe9A9cD1ce3eAfd06cb8ae3f76aA3222921391b6/sources/MyToken.sol
|
virtual means function can be overridden in the future.
|
function transfer(address _to, uint256 _value) public virtual returns (bool success) {
require(_value > 0 && _balances[msg.sender] >= _value);
_balances[_to] += _value;
_balances[msg.sender] -= _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
| 16,861,715 |
//Address: 0x8C95e60A62b8d71CC557F1fd0f9Ce011b83F8d68
//Contract name: Marijuaneum
//Balance: 0 Ether
//Verification Date: 3/14/2017
//Transacion Count: 6
// CODE STARTS HERE
pragma solidity 0.4.8;
contract tokenSpender { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
contract Marijuaneum {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
address public burnAddress;
/* This creates an array with all balances */
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed from, address indexed spender, uint value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Marijuaneum() {
initialSupply = 420000000000000;
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
name = 'Marijuaneum'; // Set the name for display purposes
symbol = 'XMJ'; // Set the symbol for display purposes
decimals = 8; // Amount of decimals for display purposes
burnAddress = 0x1b32000000000000000000000000000000000000;
}
function totalSupply() returns(uint){
return initialSupply - balanceOf[burnAddress];
}
/* Send coins */
function transfer(address _to, uint256 _value)
returns (bool success) {
if (balanceOf[msg.sender] >= _value && _value > 0) {
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else return false;
}
/* Allow another contract to spend some tokens in your behalf */
function approveAndCall(address _spender,
uint256 _value,
bytes _extraData)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
tokenSpender spender = tokenSpender(_spender);
spender.receiveApproval(msg.sender, _value, this, _extraData);
Approval(msg.sender, _spender, _value);
return true;
}
/*Allow another adress to use your money but doesn't notify it*/
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from,
address _to,
uint256 _value)
returns (bool success) {
if (balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && _value > 0) {
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
return true;
} else return false;
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
}
|
Public variables of the token / This creates an array with all balances / This generates a public event on the blockchain that will notify clients / Initializes contract with initial supply tokens to the creator of the contract /
|
function Marijuaneum() {
initialSupply = 420000000000000;
burnAddress = 0x1b32000000000000000000000000000000000000;
}
| 5,409,729 |
./full_match/137/0xC76d699Dac2c750DA123A997aF721a76e4534E82/sources/contracts/Stake.sol
|
View function to see pending Reward on frontend.
|
function pendingReward(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 accPerShare = pool.accPerShare;
if (block.number > pool.lastRewardBlock && totalStaked != 0) {
uint256 multiplier = block.number.sub(pool.lastRewardBlock);
uint256 tokenReward = multiplier.mul(rewardPerBlock);
accPerShare = accPerShare.add(tokenReward.mul(1e12).div(totalStaked));
}
uint256 remainingRewards = IERC20(ERC20).balanceOf(address(this));
uint256 rewards = user.amount.mul(accPerShare).div(1e12).sub(user.rewardDebt);
if (remainingRewards == 0) {
rewards = 0;
rewards = remainingRewards;
}
return rewards;
}
| 4,777,971 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
/**
* @title AirSwap Staking: Stake and Unstake Tokens
* @notice https://www.airswap.io/
*/
contract Staking is Ownable {
using SafeERC20 for ERC20;
using SafeMath for uint256;
struct Stake {
uint256 duration;
uint256 cliff;
uint256 initial;
uint256 balance;
uint256 timestamp;
}
// Token to be staked
ERC20 public immutable token;
// Vesting duration and cliff
uint256 public duration;
uint256 public cliff;
// Mapping of account to stakes
mapping(address => Stake[]) public allStakes;
// ERC-20 token properties
string public name;
string public symbol;
// ERC-20 Transfer event
event Transfer(address indexed from, address indexed to, uint256 tokens);
/**
* @notice Constructor
* @param _token address
* @param _name string
* @param _symbol string
* @param _duration uint256
* @param _cliff uint256
*/
constructor(
ERC20 _token,
string memory _name,
string memory _symbol,
uint256 _duration,
uint256 _cliff
) {
token = _token;
name = _name;
symbol = _symbol;
duration = _duration;
cliff = _cliff;
}
/**
* @notice Set vesting config
* @param _duration uint256
* @param _cliff uint256
*/
function setVesting(uint256 _duration, uint256 _cliff) external onlyOwner {
duration = _duration;
cliff = _cliff;
}
/**
* @notice Set metadata config
* @param _name string
* @param _symbol string
*/
function setMetaData(string memory _name, string memory _symbol)
external
onlyOwner
{
name = _name;
symbol = _symbol;
}
/**
* @notice Stake tokens
* @param amount uint256
*/
function stake(uint256 amount) external {
stakeFor(msg.sender, amount);
}
/**
* @notice Extend a stake
* @param amount uint256
*/
function extend(uint256 index, uint256 amount) external {
extendFor(index, msg.sender, amount);
}
/**
* @notice Unstake multiple
* @param amounts uint256[]
*/
function unstake(uint256[] calldata amounts) external {
uint256 totalAmount = 0;
uint256 length = amounts.length;
while (length > 0) {
length = length - 1;
if (amounts[length] > 0) {
_unstake(length, amounts[length]);
totalAmount += amounts[length];
}
}
if (totalAmount > 0) {
token.transfer(msg.sender, totalAmount);
emit Transfer(msg.sender, address(0), totalAmount);
}
}
/**
* @notice All stakes for an account
* @param account uint256
*/
function getStakes(address account)
external
view
returns (Stake[] memory stakes)
{
uint256 length = allStakes[account].length;
stakes = new Stake[](length);
while (length > 0) {
length = length - 1;
stakes[length] = allStakes[account][length];
}
return stakes;
}
/**
* @notice Total balance of all accounts (ERC-20)
*/
function totalSupply() external view returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @notice Balance of an account (ERC-20)
*/
function balanceOf(address account) external view returns (uint256 total) {
Stake[] memory stakes = allStakes[account];
uint256 length = stakes.length;
while (length > 0) {
length = length - 1;
total = total.add(stakes[length].balance);
}
return total;
}
/**
* @notice Decimals of underlying token (ERC-20)
*/
function decimals() external view returns (uint8) {
return token.decimals();
}
/**
* @notice Stake tokens for an account
* @param account address
* @param amount uint256
*/
function stakeFor(address account, uint256 amount) public {
require(amount > 0, "AMOUNT_INVALID");
allStakes[account].push(
Stake(duration, cliff, amount, amount, block.timestamp)
);
token.safeTransferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), account, amount);
}
/**
* @notice Extend a stake for an account
* @param index uint256
* @param account address
* @param amount uint256
*/
function extendFor(
uint256 index,
address account,
uint256 amount
) public {
require(amount > 0, "AMOUNT_INVALID");
Stake storage selected = allStakes[account][index];
// If selected stake is fully vested create a new stake
if (vested(account, index) == selected.initial) {
stakeFor(account, amount);
} else {
uint256 newInitial = selected.initial.add(amount);
uint256 newBalance = selected.balance.add(amount);
// Calculate a new timestamp proportional to the new amount
// New timestamp limited to current timestamp (amount / newInitial approaches 1)
uint256 newTimestamp = selected.timestamp +
amount.mul(block.timestamp.sub(selected.timestamp)).div(newInitial);
allStakes[account][index] = Stake(
duration,
cliff,
newInitial,
newBalance,
newTimestamp
);
token.safeTransferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), account, amount);
}
}
/**
* @notice Vested amount for an account
* @param account uint256
* @param index uint256
*/
function vested(address account, uint256 index)
public
view
returns (uint256)
{
Stake storage stakeData = allStakes[account][index];
if (block.timestamp.sub(stakeData.timestamp) > duration) {
return stakeData.initial;
}
return
stakeData.initial.mul(block.timestamp.sub(stakeData.timestamp)).div(
stakeData.duration
);
}
/**
* @notice Available amount for an account
* @param account uint256
* @param index uint256
*/
function available(address account, uint256 index)
public
view
returns (uint256)
{
Stake memory selected = allStakes[account][index];
if (block.timestamp.sub(selected.timestamp) < selected.cliff) {
return 0;
}
return vested(account, index) - (selected.initial - selected.balance);
}
/**
* @notice Unstake tokens
* @param index uint256
* @param amount uint256
*/
function _unstake(uint256 index, uint256 amount) internal {
require(index < allStakes[msg.sender].length, "INDEX_OUT_OF_RANGE");
Stake storage selected = allStakes[msg.sender][index];
require(
block.timestamp.sub(selected.timestamp) >= selected.cliff,
"CLIFF_NOT_REACHED"
);
require(amount <= available(msg.sender, index), "AMOUNT_EXCEEDS_AVAILABLE");
selected.balance = selected.balance.sub(amount);
if (selected.balance == 0) {
Stake[] memory stakes = allStakes[msg.sender];
allStakes[msg.sender][index] = stakes[stakes.length.sub(1)];
allStakes[msg.sender].pop();
}
}
}
|
Extend a stake for an account index uint256 account address amount uint256/ If selected stake is fully vested create a new stake Calculate a new timestamp proportional to the new amount New timestamp limited to current timestamp (amount / newInitial approaches 1)
|
function extendFor(
uint256 index,
address account,
uint256 amount
) public {
require(amount > 0, "AMOUNT_INVALID");
Stake storage selected = allStakes[account][index];
if (vested(account, index) == selected.initial) {
stakeFor(account, amount);
uint256 newInitial = selected.initial.add(amount);
uint256 newBalance = selected.balance.add(amount);
uint256 newTimestamp = selected.timestamp +
amount.mul(block.timestamp.sub(selected.timestamp)).div(newInitial);
allStakes[account][index] = Stake(
duration,
cliff,
newInitial,
newBalance,
newTimestamp
);
token.safeTransferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), account, amount);
}
}
| 2,549,072 |
/**
*Submitted for verification at Etherscan.io on 2021-03-11
*/
// SPDX-License-Identifier: MIT
// 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);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// File: contracts/strategies/StabilizeStrategyStablecoinArbV4.sol
pragma solidity ^0.6.6;
// This is iteration 3 of the strategy
// This is a strategy that takes advantage of arb opportunities for multiple stablecoins
// Users deposit various stables into the strategy and the strategy will sell into the lowest priced token
// In addition to that, the pool will earn interest in the form of aTokens from Aave
// Selling will occur via Curve and buying WETH via Sushiswap
// Half the profit earned from the sell and interest will be used to buy WETH and split it among the treasury, stakers and executor
// Half will remain as stables (in the form of aTokens)
// It will sell on withdrawals only when a non-contract calls it and certain requirements are met
// Anyone can be an executors and profit a percentage on a trade
// Gas cost is reimbursed, up to a percentage of the total WETH profit / stipend
// This strategy doesn't store stables but rather interest earning variants (aTokens)
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
interface StabilizePriceOracle {
function getPrice(address _address) external view returns (uint256);
}
interface CurvePool {
function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange(int128, int128, uint256, uint256) external; // Exchange tokens
}
interface TradeRouter {
function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory);
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory);
function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
interface LendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
}
interface LendingPool {
function withdraw(address, uint256, address) external returns (uint256);
function deposit(address, uint256, address, uint16) external;
}
interface StrategyVault {
function viewWETHProfit(uint256) external view returns (uint256);
function sendWETHProfit() external;
}
contract StabilizeStrategyStablecoinArbV4 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
address public stakingAddress; // Address to the STBZ staking pool
address public zsTokenAddress; // The address of the controlling zs-Token
address public strategyVaultAddress; // This strategy stores interest aTokens in separate vault
uint256 constant DIVISION_FACTOR = 100000;
uint256 public lastTradeTime;
uint256 public lastActionBalance; // Balance before last deposit, withdraw or trade
bool public daiOpenTrade = true; // If true, dai can trade openly with other tokens other than susd
uint256 public percentTradeTrigger = 90000; // 90% change in value will trigger a trade
uint256 public percentSell = 50000; // 50% of the tokens are sold to the cheapest token
uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains (including interest)
uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor
uint256 public percentStakers = 50000; // 50% of non-executor WETH goes to stakers, can be changed, rest goes to treasury
uint256 public minTradeSplit = 20000; // If the balance of a stablecoin is less than or equal to this, it trades the entire balance
uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent
uint256 public gasStipend = 1000000; // This is the gas units that are covered by executing a trade taken from the WETH profit
uint256 constant minGain = 1e16; // Minimum amount of stablecoin gain (about 0.01 USD) before buying WETH and splitting it
// Token information
// This strategy accepts multiple stablecoins
// DAI, USDC, USDT, sUSD
struct TokenInfo {
IERC20 token; // Reference of token
IERC20 aToken; // Reference to its aToken (Aave v2)
uint256 decimals; // Decimals of token
uint256 price; // Last price of token in USD
uint256 lastATokenBalance; // The balance the last time the interest was calculated
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
StabilizePriceOracle private oracleContract; // A reference to the price oracle contract
// Strategy specific variables
address constant CURVE_DAI_SUSD = address(0xEB16Ae0052ed37f479f7fe63849198Df1765a733); // Curve pool for 2 tokens, asUSD, aDAI
address constant CURVE_ATOKEN_3 = address(0xDeBF20617708857ebe4F679508E7b7863a8A8EeE); // Curve pool for 3 tokens, aDAI, aUSDT, aUSDC
address constant SUSHISWAP_ROUTER = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //Address of Sushiswap
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
address constant LENDING_POOL_ADDRESS_PROVIDER = address(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); // Provider for Aave addresses
constructor(
address _treasury,
address _staking,
address _zsToken,
StabilizePriceOracle _oracle
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
oracleContract = _oracle;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// Start with DAI
IERC20 _token = IERC20(address(0x6B175474E89094C44Da98b954EedeAC495271d0F));
IERC20 _aToken = IERC20(address(0x028171bCA77440897B824Ca71D1c56caC55b68A3)); // aDAI
tokenList.push(
TokenInfo({
token: _token,
aToken: _aToken,
decimals: _token.decimals(), // Aave tokens share decimals with normal tokens
price: 1e18,
lastATokenBalance: 0
})
);
// USDC
_token = IERC20(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48));
_aToken = IERC20(address(0xBcca60bB61934080951369a648Fb03DF4F96263C)); // aUSDC
tokenList.push(
TokenInfo({
token: _token,
aToken: _aToken,
decimals: _token.decimals(),
price: 1e18,
lastATokenBalance: 0
})
);
// USDT
_token = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));
_aToken = IERC20(address(0x3Ed3B47Dd13EC9a98b44e6204A523E766B225811)); // aUSDT
tokenList.push(
TokenInfo({
token: _token,
aToken: _aToken,
decimals: _token.decimals(),
price: 1e18,
lastATokenBalance: 0
})
);
// sUSD
_token = IERC20(address(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51));
_aToken = IERC20(address(0x6C5024Cd4F8A59110119C56f8933403A539555EB)); //aSUSD
tokenList.push(
TokenInfo({
token: _token,
aToken: _aToken,
decimals: _token.decimals(),
price: 1e18,
lastATokenBalance: 0
})
);
}
// Modifier
modifier onlyZSToken() {
require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
_;
}
// Read functions
function rewardTokensCount() external view returns (uint256) {
return tokenList.length;
}
function rewardTokenAddress(uint256 _pos) external view returns (address) {
require(_pos < tokenList.length,"No token at that position");
return address(tokenList[_pos].token);
}
function balanceWithInterest() public view returns (uint256) {
return getNormalizedTotalBalance(address(this)); // This will return the total balance including interest gained
}
function balance() public view returns (uint256) {
// This excludes balance that is expected to go to the vault after interest calculation
uint256 _interestBalance = balanceWithInterest();
if(lastActionBalance < _interestBalance){
return lastActionBalance.add(_interestBalance.sub(lastActionBalance).mul(percentDepositor).div(DIVISION_FACTOR));
}else{
return _interestBalance;
}
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
// Get the balance of the atokens+tokens at this address
uint256 _balance = 0;
uint256 _length = tokenList.length;
for(uint256 i = 0; i < _length; i++){
uint256 _bal = tokenList[i].aToken.balanceOf(_address).add(tokenList[i].token.balanceOf(_address));
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
// This function will return the address and amount of the token with the lowest price
uint256 length = tokenList.length;
uint256 targetID = 0;
uint256 targetPrice = 0;
for(uint256 i = 0; i < length; i++){
if(tokenList[i].aToken.balanceOf(address(this)) > 0){
uint256 _price = tokenList[i].price;
if(targetPrice == 0 || _price <= targetPrice){
targetPrice = _price;
targetID = i;
}
}
}
if(targetPrice > 0){
return (address(tokenList[targetID].token), tokenList[targetID].aToken.balanceOf(address(this)));
}else{
return (address(0), 0); // No balance
}
}
// Write functions
function enter() external onlyZSToken {
deposit(false);
}
function exit() external onlyZSToken {
// The ZS token vault is removing all tokens from this strategy
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
// First the interest earned since the last call will be calculated
// Some will sent to a strategy vault to be later processed when it becomes large enough
calculateAndStoreInterest(); // This function will also call an update to lastATokenBalance
// Then convert deposited stablecoins into their aToken equivalents and updates lastATokenBalance
convertAllToAaveTokens();
// No trading is performed on deposit
if(nonContract == true){}
lastActionBalance = balanceWithInterest(); // This action balance represents pool post stablecoin deposit
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balanceWithInterest() > 0, "There are no tokens in this strategy");
// First the interest earned since the last call will be calculated and sent to vault
calculateAndStoreInterest();
// This is in case there are some leftover raw tokens
convertAllToAaveTokens();
if(nonContract == true){
if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
checkAndSwapTokens(address(0)); // This will also not call calculateAndHold due to 0 address
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balanceWithInterest();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerPrice(_depositor, _myBalance, false); // This will withdraw based on token price
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerPrice(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balanceWithInterest();
return withdrawAmount;
}
// Get price from chainlink oracle
function updateTokenPrices() internal {
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
uint256 price = oracleContract.getPrice(address(tokenList[i].token));
if(price > 0){
tokenList[i].price = price;
}
}
}
// This will withdraw the tokens from the contract based on their price, from lowest price to highest
function withdrawPerPrice(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
uint256 _balance = 0;
if(_takeAll == true){
// We will empty out the strategy
for(uint256 i = 0; i < length; i++){
_balance = tokenList[i].aToken.balanceOf(address(this));
if(_balance > 0){
// Convert the entire a tokens to token
convertFromAToken(i, _balance);
tokenList[i].lastATokenBalance = tokenList[i].aToken.balanceOf(address(this));
}
_balance = tokenList[i].token.balanceOf(address(this));
if(_balance > 0){
// Now send the normal token back
tokenList[i].token.safeTransfer(_receiver, _balance);
}
}
return;
}
bool[4] memory done;
uint256 targetID = 0;
uint256 targetPrice = 0;
updateTokenPrices(); // Update the prices based on an off-chain Oracle
for(uint256 i = 0; i < length; i++){
targetPrice = 0; // Reset the target price
// Find the lowest priced token to withdraw
for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _price = tokenList[i2].price;
if(targetPrice == 0 || _price <= targetPrice){
targetPrice = _price;
targetID = i2;
}
}
}
done[targetID] = true;
// Determine the balance left
uint256 _normalizedBalance = tokenList[targetID].aToken.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
_balance = tokenList[targetID].aToken.balanceOf(address(this));
convertFromAToken(targetID, _balance);
tokenList[targetID].lastATokenBalance = tokenList[targetID].aToken.balanceOf(address(this));
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
_balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
_withdrawAmount = 0;
convertFromAToken(targetID, _balance);
tokenList[targetID].lastATokenBalance = tokenList[targetID].aToken.balanceOf(address(this));
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function convertFromAToken(uint256 _id, uint256 amount) internal {
// This will take the aToken and convert it to main token to be used for whatever
// It will require that the amount returned is greater than or equal to amount requested
uint256 _balance = tokenList[_id].token.balanceOf(address(this));
LendingPool lender = LendingPool(LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool()); // Load the lending pool
tokenList[_id].aToken.safeApprove(address(lender), 0);
tokenList[_id].aToken.safeApprove(address(lender), amount);
lender.withdraw(address(tokenList[_id].token), amount, address(this));
require(amount >= tokenList[_id].token.balanceOf(address(this)).sub(_balance), "Aave failed to withdraw the proper balance");
}
function convertToAToken(uint256 _id, uint256 amount) internal {
// This will take the token and convert it to atoken to be used for whatever
// It will require that the amount returned is greater than or equal to amount requested
uint256 _balance = tokenList[_id].aToken.balanceOf(address(this));
LendingPool lender = LendingPool(LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool()); // Load the lending pool
tokenList[_id].token.safeApprove(address(lender), 0);
tokenList[_id].token.safeApprove(address(lender), amount);
lender.deposit(address(tokenList[_id].token), amount, address(this), 0);
require(amount >= tokenList[_id].aToken.balanceOf(address(this)).sub(_balance), "Aave failed to return proper amount of aTokens");
}
function convertAllToAaveTokens() internal {
// Convert stables to interest earning variants
uint256 length = tokenList.length;
uint256 _balance = 0;
for(uint256 i = 0; i < length; i++){
_balance = tokenList[i].token.balanceOf(address(this));
if(_balance > 0){
// Convert the entire token to a token
convertToAToken(i, _balance);
}
// Now update its balance
tokenList[i].lastATokenBalance = tokenList[i].aToken.balanceOf(address(this));
}
}
function simulateExchange(address _inputToken, address _outputToken, uint256 _amount) internal view returns (uint256) {
if(_outputToken != WETH_ADDRESS){
// When not selling for WETH, we are only dealing with aTokens
// aSUSD only can buy and sell for aDAI due to gas costs of deployment and loops
// 0 - aDAI, 1 - aUSDC, 2 - aUSDT, 3 - aSUSD
uint256 inputID = 0;
uint256 outputID = 0;
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
if(_inputToken == address(tokenList[i].aToken)){
inputID = i;
}
if(_outputToken == address(tokenList[i].aToken)){
outputID = i;
}
}
if(inputID == outputID){return 0;}
if(inputID == 3 || outputID == 3){
// Just 1 pool
int128 inCurveID = 0; // aDAI in
int128 outCurveID = 0; // aDAI out
if(inputID == 3) {inCurveID = 1;} // aUSDT in
if(outputID == 3){outCurveID = 1;} // aUSDC out
CurvePool pool = CurvePool(CURVE_DAI_SUSD);
_amount = pool.get_dy(inCurveID, outCurveID, _amount);
return _amount;
}else{
// Just 1 pool
int128 inCurveID = 0; // aDAI in
int128 outCurveID = 0; // aDAI out
if(inputID == 1) {inCurveID = 1;} // aUSDC in
if(inputID == 2) {inCurveID = 2;} // aUSDT in
if(outputID == 1){outCurveID = 1;} // aUSDC out
if(outputID == 2){outCurveID = 2;} // aUSDT out
CurvePool pool = CurvePool(CURVE_ATOKEN_3);
_amount = pool.get_dy(inCurveID, outCurveID, _amount);
return _amount;
}
}else{
// Simple Sushiswap route
// When selling for WETH, we must have already converted aToken to token
// All stables have liquid path to WETH
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER);
address[] memory path = new address[](2);
path[0] = _inputToken;
path[1] = WETH_ADDRESS;
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1];
return _amount;
}
}
function exchange(address _inputToken, address _outputToken, uint256 _amount) internal {
if(_outputToken != WETH_ADDRESS){
// When not selling for WETH, we are only dealing with aTokens
// aSUSD only can buy and sell for aDAI
// 0 - aDAI, 1 - aUSDC, 2 - aUSDT, 3 - aSUSD
uint256 inputID = 0;
uint256 outputID = 0;
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
if(_inputToken == address(tokenList[i].aToken)){
inputID = i;
}
if(_outputToken == address(tokenList[i].aToken)){
outputID = i;
}
}
if(inputID == outputID){return;}
if(inputID == 3 || outputID == 3){
// We are dealing with aSUSD
int128 inCurveID = 0; // aDAI in
int128 outCurveID = 0; // aDAI out
if(inputID == 3) {inCurveID = 1;} // aUSDT in
if(outputID == 3){outCurveID = 1;} // aUSDC out
CurvePool pool = CurvePool(CURVE_DAI_SUSD);
IERC20(_inputToken).safeApprove(CURVE_DAI_SUSD, 0);
IERC20(_inputToken).safeApprove(CURVE_DAI_SUSD, _amount);
pool.exchange(inCurveID, outCurveID, _amount, 1);
return;
}else{
// Just 1 pool
int128 inCurveID = 0; // DAI in
int128 outCurveID = 0; // DAI out
if(inputID == 1) {inCurveID = 1;} // USDC in
if(inputID == 2) {inCurveID = 2;} // USDT in
if(outputID == 1){outCurveID = 1;} // USDC out
if(outputID == 2){outCurveID = 2;} // USDT out
CurvePool pool = CurvePool(CURVE_ATOKEN_3);
IERC20(_inputToken).safeApprove(CURVE_ATOKEN_3, 0);
IERC20(_inputToken).safeApprove(CURVE_ATOKEN_3, _amount);
pool.exchange(inCurveID, outCurveID, _amount, 1);
return;
}
}else{
// Simple Sushiswap route
// When selling for WETH, we must have already converted aToken to token
// All stables have liquid path to WETH
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER);
address[] memory path = new address[](2);
path[0] = _inputToken;
path[1] = WETH_ADDRESS;
IERC20(_inputToken).safeApprove(SUSHISWAP_ROUTER, 0);
IERC20(_inputToken).safeApprove(SUSHISWAP_ROUTER, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}
}
function getCheapestCurveToken() internal view returns (uint256) {
// This will give us the ID of the cheapest token in the pool
// And it will tell us if aDAI is higher valued than aSUSD
// We will estimate the return for trading 1000 aDAI
// The higher the return, the lower the price of the other token
uint256 targetID = 0; // Our target ID is aDAI first
uint256 aDaiAmount = uint256(1000).mul(10**tokenList[0].decimals);
uint256 highAmount = aDaiAmount;
uint256 length = tokenList.length;
for(uint256 i = 1; i < length; i++){
uint256 estimate = simulateExchange(address(tokenList[0].aToken), address(tokenList[i].aToken), aDaiAmount);
// Normalize the estimate into DAI decimals
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[i].decimals);
if(estimate > highAmount){
// This token is worth less than the aDAI
highAmount = estimate;
targetID = i;
}
}
return targetID;
}
function calculateAndStoreInterest() internal {
// This function will take the difference between the last aToken balance and current and distribute some of it to the strategy vault
uint256 length = tokenList.length;
uint256 _balance = 0;
for(uint256 i = 0; i < length; i++){
_balance = tokenList[i].aToken.balanceOf(address(this)); // Get the current balance
if(_balance > tokenList[i].lastATokenBalance){
uint256 chargeableGain = _balance.sub(tokenList[i].lastATokenBalance).mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR);
// Convert the chargeableGain to token then to WETH
if(chargeableGain > 0){
// Instead of convert aTokens to weth right away, store them in a separate contract, saving gas
tokenList[i].aToken.safeTransfer(strategyVaultAddress, chargeableGain);
}
}
tokenList[i].lastATokenBalance = tokenList[i].aToken.balanceOf(address(this)); // The the current aToken amount
}
}
function calculateAndViewInterest() internal view returns (uint256) {
// This function will take the difference between the last aToken balance and current and return the calculated normalized interest gain
uint256 length = tokenList.length;
uint256 _balance = 0;
uint256 gain = 0;
for(uint256 i = 0; i < length; i++){
_balance = tokenList[i].aToken.balanceOf(address(this)); // Get the current balance
if(_balance > tokenList[i].lastATokenBalance){
// Just normalize the difference into gain
gain = gain.add(_balance.sub(tokenList[i].lastATokenBalance).mul(1e18).div(10**tokenList[i].decimals));
}
}
// Gain will be normalized and represent total gain from interest
return gain;
}
function getFastGasPrice() internal view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
function checkAndSwapTokens(address _executor) internal {
lastTradeTime = now;
if(_executor != address(0)){
calculateAndStoreInterest(); // It will send aTokens to strategy vault
}
StrategyVault vault = StrategyVault(strategyVaultAddress);
vault.sendWETHProfit(); // This will request the vault convert and send WETH to the strategy to be distributed
// Now find our target token to sell into
uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap token than Chainlink
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _totalBalance = balanceWithInterest(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 localTarget = targetID;
if(i == 0){
if(daiOpenTrade == false){ // If governance prevents dai from trading for usdc and usdt
localTarget = 3; // aDAI will only sell for aSUSD as they switch often
}
}else if(i == 3){
localTarget = 0; // aSUSD will only sell for aDAI
}else{
if(localTarget == 3){continue;} // Other tokens can't buy aSUSD via curve
}
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(tokenList[i].aToken.balanceOf(address(this)) <= _minTradeTarget){
// We have a small amount of tokens to sell, so sell all of it
sellBalance = tokenList[i].aToken.balanceOf(address(this));
}else{
sellBalance = tokenList[i].aToken.balanceOf(address(this)).mul(percentSell).div(DIVISION_FACTOR);
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].aToken), address(tokenList[localTarget].aToken), sellBalance);
if(estimate > minReceiveBalance){
_expectIncrease = true;
// We are getting a greater number of tokens, complete the exchange
exchange(address(tokenList[i].aToken), address(tokenList[localTarget].aToken), sellBalance);
}
}
}
}
uint256 _newBalance = balanceWithInterest();
if(_expectIncrease == true){
// There may be rare scenarios where we don't gain any by calling this function
require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
}
uint256 gain = _newBalance.sub(_totalBalance);
IERC20 weth = IERC20(WETH_ADDRESS);
uint256 _wethBalance = weth.balanceOf(address(this));
if(gain >= minGain || _wethBalance > 0){
// Minimum gain required to buy WETH is about $0.01
if(gain >= minGain){
// Buy WETH from Sushiswap with stablecoin
uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18);
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
if(sellBalance <= tokenList[targetID].aToken.balanceOf(address(this))){
// Convert from aToken to Token
convertFromAToken(targetID, sellBalance);
// Buy WETH
exchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance);
_wethBalance = weth.balanceOf(address(this));
}
}
if(_wethBalance > 0){
// This is pure profit, figure out allocation
// Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
// Executors will get a gas reimbursement in WETH and a percent of the remaining
uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested
if(gasFee > maxGasFee){
gasFee = maxGasFee; // Gas fee cannot be greater than the maximum
}
uint256 executorAmount = gasFee;
if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){
executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point
}else{
// Add the executor percent on top of gas fee
executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee);
}
if(executorAmount > 0){
weth.safeTransfer(_executor, executorAmount);
_wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract
}
}
if(_wethBalance > 0){
uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR);
uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
if(treasuryAmount > 0){
weth.safeTransfer(treasuryAddress, treasuryAmount);
}
if(stakersAmount > 0){
if(stakingAddress != address(0)){
weth.safeTransfer(stakingAddress, stakersAmount);
StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
}else{
// No staking pool selected, just send to the treasury
weth.safeTransfer(treasuryAddress, stakersAmount);
}
}
}
}
}
for(uint256 i = 0; i < length; i++){
// Now run this through again and update all the token balances to prevent being affected by interest calculator
tokenList[i].lastATokenBalance = tokenList[i].aToken.balanceOf(address(this));
}
}
function expectedProfit(bool inWETHForExecutor) external view returns (uint256) {
// This view will return the expected profit in wei units that a trading activity will have on the pool
uint256 interestGain = calculateAndViewInterest(); // Will return total gain (normalized)
if(inWETHForExecutor == true){
StrategyVault vault = StrategyVault(strategyVaultAddress);
// The first param is used to determine if interest earned will bring it over threshold
interestGain = vault.viewWETHProfit(interestGain); // Will return profit as WETH
}
// Now find our target token to sell into
uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap token than Chainlink
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _normalizedGain = 0;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 localTarget = targetID;
if(i == 0){
if(daiOpenTrade == false){
localTarget = 3; // aDAI will only sell for aSUSD as they switch often
}
}else if(i == 3){
localTarget = 0; // aSUSD will only sell for aDAI
}else{
if(localTarget == 3){continue;} // Other tokens can't buy aSUSD via curve
}
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(tokenList[i].aToken.balanceOf(address(this)) <= _minTradeTarget){
// We have a small amount of tokens to sell, so sell all of it
sellBalance = tokenList[i].aToken.balanceOf(address(this));
}else{
sellBalance = tokenList[i].aToken.balanceOf(address(this)).mul(percentSell).div(DIVISION_FACTOR);
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].aToken), address(tokenList[localTarget].aToken), sellBalance);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[localTarget].decimals); // Normalized gain
_normalizedGain = _normalizedGain.add(_gain);
}
}
}
}
if(inWETHForExecutor == false){
return _normalizedGain.add(interestGain);
}else{
// Calculate WETH profit
if(_normalizedGain.add(interestGain) == 0){
return 0;
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = interestGain; // WETH earned from interest alone
if(_normalizedGain > 0){
uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
// Estimate output
estimate = estimate.add(simulateExchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance));
}
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total
return estimate.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get max percent of total
}else{
estimate = estimate.sub(gasFee); // Subtract fee from remaining balance
return estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); // Executor amount with fee added
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade) external {
// Function designed to promote trading with incentive. Users get percentage of WETH from profitable trades
require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor);
lastActionBalance = balanceWithInterest();
}
// Governance functions
function governanceSwapTokens() external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(_msgSender());
lastActionBalance = balanceWithInterest();
}
function governanceToggleDaiTrade() external onlyGovernance {
// Governance can open or close dai open trade
if(daiOpenTrade == false){
daiOpenTrade = true;
}else{
daiOpenTrade = false;
}
}
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256[6] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(balanceWithInterest() > 0){ // Timelock only applies when balance exists
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the staking address
// --------------------
function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) {
stakingAddress = _timelock_address;
}
// --------------------
// Change the zsToken address
// --------------------
function startChangeZSToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) {
zsTokenAddress = _timelock_address;
}
// --------------------
// Change the price oracle contract used, in case of upgrades
// --------------------
function startChangePriceOracle(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 5;
_timelock_address = _address;
}
function finishChangePriceOracle() external onlyGovernance timelockConditionsMet(5) {
oracleContract = StabilizePriceOracle(_timelock_address);
}
// --------------------
// Change the trading conditions used by the strategy
// --------------------
function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, uint256 _minSplit, uint256 _maxStipend, uint256 _pMaxStipend) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data[0] = _pTradeTrigger;
_timelock_data[1] = _pSellPercent;
_timelock_data[2] = _minSplit;
_timelock_data[3] = _maxStipend;
_timelock_data[4] = _pMaxStipend;
}
function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(6) {
percentTradeTrigger = _timelock_data[0];
percentSell = _timelock_data[1];
minTradeSplit = _timelock_data[2];
gasStipend = _timelock_data[3];
maxPercentStipend = _timelock_data[4];
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 7;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(7) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
}
// --------------------
// Remove tokens not used in strategy from strategy
// --------------------
function startRecoverTrappedToken(address _token) external onlyGovernance {
uint256 length = tokenList.length;
// Can only remove non-strategy tokens
for(uint256 i = 0; i < length; i++){
require(_token != address(tokenList[i].token) && _token != address(tokenList[i].aToken), "Can only extract non-native tokens from strategy");
}
_timelockStart = now;
_timelockType = 8;
_timelock_address = _token;
}
function finishRecoverTrappedToken() external onlyGovernance timelockConditionsMet(8) {
IERC20 token = IERC20(_timelock_address);
token.safeTransfer(governance(), token.balanceOf(address(this)));
}
// --------------------
// Change the strategy vault address
// --------------------
function startChangeStrategyVault(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 9;
_timelock_address = _address;
}
function finishChangeStrategyVault() external onlyGovernance timelockConditionsMet(9) {
strategyVaultAddress = _timelock_address;
}
// --------------------
}
|
Change the price oracle contract used, in case of upgrades --------------------
|
function startChangePriceOracle(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 5;
_timelock_address = _address;
}
| 2,108,608 |
/* FOOToken */
/* Released on 11.11.2018 v.1.0 */
/* To celebrate 100 years of Polish */
/* INDEPENDENCE */
/* ==================================== */
/* National Independence Day is a */
/* national day in Poland celebrated on */
/* 11 November to commemorate the */
/* anniversary of the restoration of */
/* Poland's sovereignty as the */
/* Second Polish Republic in 1918 from */
/* German, Austrian and Russian Empires */
/* Following the partitions in the late */
/* 18th century, Poland ceased to exist */
/* for 123 years until the end of */
/* World War I, when the destruction of */
/* the neighbouring powers allowed the */
/* country to reemerge. */
pragma solidity ^0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC223Interface {
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public ;
function transfer(address to, uint value, bytes data) public ;
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
/**
* @title Contract that will work with ERC223 tokens.
*/
contract ERC223ReceivingContract {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @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 Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract FOOToken is IERC20, ERC223Interface, Ownable, Pausable {
using SafeMath for uint;
mapping(address => uint) balances; // List of user balances.
mapping (address => mapping (address => uint256)) private _allowed;
modifier validDestination( address to ) {
require(to != address(0x0));
_;
}
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
constructor() public {
_name = "FOOToken";
_symbol = "FOOT";
_decimals = 18;
_mint(msg.sender, 100000000 * (10 ** 18));
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
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 increaseAllowance(
address spender,
uint256 addedValue
)
public
whenNotPaused
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
whenNotPaused
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
validDestination(_to)
public
whenNotPaused
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);
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(_from, _value, empty);
}
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) whenNotPaused validDestination(_to) public {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value, _data);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _account The account that will receive the created tokens.
* @param _amount The amount that will be created.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != 0);
_totalSupply = _totalSupply.add(_amount);
balances[_account] = balances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_account)
}
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_account);
receiver.tokenFallback(address(0), _amount, empty);
}
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint _value) whenNotPaused validDestination(_to) public {
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value, empty);
}
/**
* @dev Returns balance of the `_owner`.
*
* @param _owner The address whose balance will be returned.
* @return balance Balance of the `_owner`.
*/
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
// Don't accept direct payments
function() public payable {
revert();
}
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) pure public {
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
*/
}
}
|
Transfer the specified amount of tokens to the specified address. This function works the same with the previous one but doesn't contain `_data` param. Added due to backwards compatibility reasons. _to Receiver address. _value Amount of tokens that will be transferred./ Retrieve the size of the code on target address, this needs assembly .
|
function transfer(address _to, uint _value) whenNotPaused validDestination(_to) public {
uint codeLength;
bytes memory empty;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value, empty);
}
| 12,655,366 |
./full_match/1/0x9d52DdE1B84264fE42fAffa58741842E4d6AF02E/sources/BuildaInu.sol
|
SPDX-License-Identifier: Unlicensed
|
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);
Innovative Customized NFT platform - Create Your Unique piece of Inu History! $Binu Builda Inu
}
| 5,011,462 |
/**
*Submitted for verification at Etherscan.io on 2020-11-05
*/
/*
website: bns.finance
This project is freshly written to change the way ICO is done.
BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNNN SSSSSSSSSSSSSSS DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFIIIIIIIIII
B::::::::::::::::B N:::::::N N::::::N SS:::::::::::::::S D::::::::::::DDD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I
B::::::BBBBBB:::::B N::::::::N N::::::NS:::::SSSSSS::::::S D:::::::::::::::DD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I
BB:::::B B:::::BN:::::::::N N::::::NS:::::S SSSSSSS DDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::EFF::::::FFFFFFFFF::::FII::::::II
B::::B B:::::BN::::::::::N N::::::NS:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F FFFFFF I::::I
B::::B B:::::BN:::::::::::N N::::::NS:::::S D:::::D D:::::DE:::::E F:::::F I::::I
B::::BBBBBB:::::B N:::::::N::::N N::::::N S::::SSSS D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I
B:::::::::::::BB N::::::N N::::N N::::::N SS::::::SSSSS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I
B::::BBBBBB:::::B N::::::N N::::N:::::::N SSS::::::::SS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I
B::::B B:::::BN::::::N N:::::::::::N SSSSSS::::S D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I
B::::B B:::::BN::::::N N::::::::::N S:::::S D:::::D D:::::DE:::::E F:::::F I::::I
B::::B B:::::BN::::::N N:::::::::N S:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F I::::I
BB:::::BBBBBB::::::BN::::::N N::::::::NSSSSSSS S:::::S DDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::EFF:::::::FF II::::::II
B:::::::::::::::::B N::::::N N:::::::NS::::::SSSSSS:::::S ...... D:::::::::::::::DD E::::::::::::::::::::EF::::::::FF I::::::::I
B::::::::::::::::B N::::::N N::::::NS:::::::::::::::SS .::::. D::::::::::::DDD E::::::::::::::::::::EF::::::::FF I::::::::I
BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNN SSSSSSSSSSSSSSS ...... DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFF IIIIIIIIII
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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, "SAO");
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, "SMO");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "IB");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "RR");
}
/**
* @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, "IBC");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "CNC");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length != 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "DAB0");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "LF1");
if (returndata.length != 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "LF2");
}
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 public _totalSupply;
string public _name;
string public _symbol;
uint8 public _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
// /**
// * @dev Returns the name of the token.
// */
// function name() public view returns (string memory) {
// return _name;
// }
// /**
// * @dev Returns the symbol of the token, usually a shorter version of the
// * name.
// */
// function symbol() public view returns (string memory) {
// return _symbol;
// }
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
// function decimals() public view returns (uint8) {
// return _decimals;
// }
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ISA");
require(recipient != address(0), "IRA");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "TIF");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "M0");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "B0");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "BIB");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "IA");
require(spender != address(0), "A0");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// /**
// * @dev Sets {decimals} to a value other than the default one of 18.
// *
// * WARNING: This function should only be called from the constructor. Most
// * applications that interact with token contracts will not expect
// * {decimals} to ever change, and may work incorrectly if it does.
// */
// function _setupDecimals(uint8 decimals_) internal {
// _decimals = decimals_;
// }
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
contract BnsdLaunchPool is Context {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of a raising pool.
struct RaisePoolInfo {
IERC20 raiseToken; // Address of raising token contract.
uint256 maxTokensPerPerson; // Maximum tokens a user can buy.
uint256 totalTokensOnSale; // Total tokens available on offer.
uint256 startBlock; // When the sale starts
uint256 endBlock; // When the sale ends
uint256 totalTokensSold; // Total tokens sold to users so far
uint256 tokensDeposited; // Total ICO tokens deposited
uint256 votes; // Voted by users
address owner; // Owner of the pool
bool updateLocked; // No pool info can be updated once this is turned ON
bool balanceAdded; // Whether ICO tokens are added in correct amount
bool paymentMethodAdded; // Supported currencies added or not
string poolName; // Human readable string name of the pool
}
struct AirdropPoolInfo {
uint256 totalTokensAvailable; // Total tokens staked so far.
IERC20 airdropToken; // Address of staking LP token.
bool airdropExists;
}
// Info of a raising pool.
struct UseCasePoolInfo {
uint256 tokensAllocated; // Total tokens available for this use
uint256 tokensClaimed; // Total tokens claimed
address reserveAdd; // Address where tokens will be released for that usecase.
bool tokensDeposited; // No pool info can be updated once this is turned ON
bool exists; // Whether reserve already exists for a pool
string useName; // Human readable string name of the pool
uint256[] unlock_perArray; // Release percent for usecase
uint256[] unlock_daysArray; // Release days for usecase
}
struct DistributionInfo {
uint256[] percentArray; // Percentage of tokens to be unlocked every phase
uint256[] daysArray; // Days from the endDate when tokens starts getting unlocked
}
// The BNSD TOKEN!
address public timeLock;
// Dev address.
address public devaddr;
// Temp dev address while switching
address private potentialAdmin;
// To store owner diistribution info after sale ends
mapping (uint256 => DistributionInfo) private ownerDistInfo;
// To store user distribution info after sale ends
mapping (uint256 => DistributionInfo) private userDistInfo;
// To store tokens on sale and their rates
mapping (uint256 => mapping (address => uint256)) public saleRateInfo;
// To store invite codes and corresponding token address and pool owners, INVITE CODE => TOKEN => OWNER => bool
mapping (uint256 => mapping (address => mapping (address => bool))) private inviteCodeList;
// To store user contribution for a sale - POOL => USER => USDT
mapping (uint256 => mapping (address => mapping (address => uint256))) public userDepositInfo;
// To store total token promised to a user - POOL => USER
mapping (uint256 => mapping (address => uint256)) public userTokenAllocation;
// To store total token claimed by a user already
mapping (uint256 => mapping (address => uint256)) public userTokenClaimed;
// To store total token redeemed by users after sale
mapping (uint256 => uint256) public totalTokenClaimed;
// To store total token raised by a project - POOL => TOKEN => AMT
mapping (uint256 => mapping (address => uint256)) public fundsRaisedSoFar;
mapping (uint256 => address) private tempAdmin;
// To store total token claimed by a project
mapping (uint256 => mapping (address => uint256)) public fundsClaimedSoFar;
// To store addresses voted for a project - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public userVotes;
// No of blocks in a day - 6700
uint256 public constant BLOCKS_PER_DAY = 6700; // Changing to 5 for test cases
// Info of each pool on blockchain.
RaisePoolInfo[] public poolInfo;
// Info of reserve pool of any project - POOL => RESERVE_ADD => USECASEINFO
mapping (uint256 => mapping (address => UseCasePoolInfo)) public useCaseInfo;
// To store total token reserved
mapping (uint256 => uint256) public totalTokenReserved;
// To store total reserved claimed
mapping (uint256 => uint256) public totalReservedTokenClaimed;
// To store list of all sales associated with a token
mapping (address => uint256[]) public listSaleTokens;
// To store list of all currencies allowed for a sale
mapping (uint256 => address[]) public listSupportedCurrencies;
// To store list of all reserve addresses for a sale
mapping (uint256 => address[]) public listReserveAddresses;
// To check if staking is enabled on a token
mapping (address => bool) public stakingEnabled;
// To get staking weight of a token
mapping (address => uint256) public stakingWeight;
// To store sum of weight of all staking tokens
uint256 public totalStakeWeight;
// To store list of staking addresses
address[] public stakingPools;
// To store stats of staked tokens per sale
mapping (uint256 => mapping (address => uint256)) public stakedLPTokensInfo;
// To store user staked amount for a sale - POOL => USER => LP_TOKEN
mapping (uint256 => mapping (address => mapping (address => uint256))) public userStakeInfo;
// To store reward claimed by a user - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public rewardClaimed;
// To store airdrop claimed by a user - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public airdropClaimed;
// To store extra airdrop tokens withdrawn by fund raiser - POOL => BOOL
mapping (uint256 => bool) public extraAirdropClaimed;
// To store airdrop info for a sale
mapping (uint256 => AirdropPoolInfo) public airdropInfo;
// To store airdrop tokens balance of a user , TOKEN => USER => BAL
mapping (address => mapping (address => uint256)) public airdropBalances;
uint256 public fee = 300; // To be divided by 1e4 before using it anywhere => 3.00%
uint256 public constant rewardPer = 8000; // To be divided by 1e4 before using it anywhere => 80.00%
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Stake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount);
event UnStake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount);
event MoveStake(address indexed user, address indexed lptoken, uint256 pid, uint256 indexed pidnew, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event WithdrawAirdrop(address indexed user, address indexed token, uint256 amount);
event ClaimAirdrop(address indexed user, address indexed token, uint256 amount);
event AirdropDeposit(address indexed user, address indexed token, uint256 indexed pid, uint256 amount);
event AirdropExtraWithdraw(address indexed user, address indexed token, uint256 indexed pid, uint256 amount);
event Voted(address indexed user, uint256 indexed pid);
constructor() public {
devaddr = _msgSender();
}
modifier onlyAdmin() {
require(devaddr == _msgSender(), "ND");
_;
}
modifier onlyAdminOrTimeLock() {
require((devaddr == _msgSender() || timeLock == _msgSender()), "ND");
_;
}
function setTimeLockAdd(address _add) public onlyAdmin {
timeLock = _add;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function getListOfSale(address _token) external view returns (uint256[] memory) {
return listSaleTokens[_token];
}
function getUserDistPercent(uint256 _pid) external view returns (uint256[] memory) {
return userDistInfo[_pid].percentArray;
}
function getUserDistDays(uint256 _pid) external view returns (uint256[] memory) {
return userDistInfo[_pid].daysArray;
}
function getReserveUnlockPercent(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) {
return useCaseInfo[_pid][_reserveAdd].unlock_perArray;
}
function getReserveUnlockDays(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) {
return useCaseInfo[_pid][_reserveAdd].unlock_daysArray;
}
function getUserDistBlocks(uint256 _pid) external view returns (uint256[] memory) {
uint256[] memory daysArray = userDistInfo[_pid].daysArray;
uint256 endPool = poolInfo[_pid].endBlock;
for(uint256 i=0; i<daysArray.length; i++){
daysArray[i] = (daysArray[i].mul(BLOCKS_PER_DAY)).add(endPool);
}
return daysArray;
}
function getOwnerDistPercent(uint256 _pid) external view returns (uint256[] memory) {
return ownerDistInfo[_pid].percentArray;
}
function getOwnerDistDays(uint256 _pid) external view returns (uint256[] memory) {
return ownerDistInfo[_pid].daysArray;
}
// Add a new token sale to the pool. Can only be called by the person having the invite code.
function addNewPool(uint256 totalTokens, uint256 maxPerPerson, uint256 startBlock, uint256 endBlock, string memory namePool, IERC20 tokenAddress, uint256 _inviteCode) external returns (uint256) {
require(endBlock > startBlock, "ESC"); // END START COMPARISON FAILED
require(startBlock > block.number, "TLS"); // TIME LIMIT START SALE
require(maxPerPerson !=0 && totalTokens!=0, "IIP"); // INVALID INDIVIDUAL PER PERSON
require(inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()]==true,"IIC"); // INVALID INVITE CODE
poolInfo.push(RaisePoolInfo({
raiseToken: tokenAddress,
maxTokensPerPerson: maxPerPerson,
totalTokensOnSale: totalTokens,
startBlock: startBlock,
endBlock: endBlock,
poolName: namePool,
updateLocked: false,
owner: _msgSender(),
totalTokensSold: 0,
balanceAdded: false,
tokensDeposited: 0,
paymentMethodAdded: false,
votes: 0
}));
uint256 poolId = (poolInfo.length - 1);
listSaleTokens[address(tokenAddress)].push(poolId);
// This makes the invite code claimed
inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()] = false;
return poolId;
}
function _checkSumArray(uint256[] memory _percentArray) internal pure returns (bool) {
uint256 _sum;
for (uint256 i = 0; i < _percentArray.length; i++) {
_sum = _sum.add(_percentArray[i]);
}
return (_sum==10000);
}
function _checkValidDaysArray(uint256[] memory _daysArray) internal pure returns (bool) {
uint256 _lastDay = _daysArray[0];
for (uint256 i = 1; i < _daysArray.length; i++) {
if(_lastDay < _daysArray[i]){
_lastDay = _daysArray[i];
}
else {
return false;
}
}
return true;
}
function _checkUpdateAllowed(uint256 _pid) internal view{
RaisePoolInfo storage pool = poolInfo[_pid];
require(pool.updateLocked == false, "CT2"); // CRITICAL TERMINATION 2
require(pool.owner==_msgSender(), "OAU"); // OWNER AUTHORIZATION FAILED
require(pool.startBlock > block.number, "CT"); // CRITICAL TERMINATION
}
// Add rule for funds locking after sale
function updateUserDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external {
require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH
_checkUpdateAllowed(_pid);
require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
userDistInfo[_pid] = DistributionInfo({
percentArray: _percentArray,
daysArray: _daysArray
});
}
// Add rule for funds unlocking of the fund raiser after sale
function updateOwnerDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external {
require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH
_checkUpdateAllowed(_pid);
require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
ownerDistInfo[_pid] = DistributionInfo({
percentArray: _percentArray,
daysArray: _daysArray
});
}
// Lock sale detail changes in future
function lockPool(uint256 _pid) external {
require(poolInfo[_pid].paymentMethodAdded==true, "CP"); // CHECK PAYMENT METHOD FAILED
_checkUpdateAllowed(_pid);
poolInfo[_pid].updateLocked = true;
}
// Add supported currencies and their rate w.r.t token on sale
// rateToken = price of one satoshi of the token in terms of token to be raised * 1e18
// 1 BNSD = 0.00021 ETH => 1e18 BNSD Satoshi = 0.00021 * 1e18 ETH satoshi => 1 BNSD Satoshi = 0.00021 ETH satoshi => rateToken = 0.00021 * 1e18 = 21 * 1e13
// rateToken for BNSD/ETH pair = 21 * 1e13;
function addSupportedCurrencies(uint256 _pid, address _tokenRaise, uint256 rateToken) external {
_checkUpdateAllowed(_pid);
require(rateToken!=0, "IR"); // INVALID RATE
require(_tokenRaise!=address(poolInfo[_pid].raiseToken), "IT"); // INVALIID PURCHASE TOKEN
if(address(this).balance == 0){ //inject PRESENT ETHER
listSupportedCurrencies[_pid].push(_tokenRaise);
}
saleRateInfo[_pid][_tokenRaise] = rateToken;
poolInfo[_pid].paymentMethodAdded = true;
}
function getSupportedCurrencies(uint256 _pid) external view returns (address[] memory) {
return listSupportedCurrencies[_pid];
}
function _checkUpdateReserveAllowed(uint256 _pid, address _resAdd) internal view returns (bool) {
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
return (poolU.exists == false || poolU.tokensDeposited == false);
// if(poolU.exists == false || poolU.tokensDeposited == false){
// return true;
// }
// return false;
}
function addReservePool(uint256 _pid, address _reserveAdd, string memory _nameReserve, uint256 _totalTokens, uint256[] memory _perArray, uint256[] memory _daysArray) external {
_checkUpdateAllowed(_pid);
require(_checkUpdateReserveAllowed(_pid, _reserveAdd) == true, "UB"); // UPDATE RESERVE FAILED
require(_checkSumArray(_perArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
require(_perArray.length==_daysArray.length, "IAL"); // INVALID ARRAY LENGTH
if(useCaseInfo[_pid][_reserveAdd].exists == false){
listReserveAddresses[_pid].push(_reserveAdd);
}
useCaseInfo[_pid][_reserveAdd] = UseCasePoolInfo({
reserveAdd: _reserveAdd,
useName: _nameReserve,
tokensAllocated: _totalTokens,
unlock_perArray: _perArray,
unlock_daysArray: _daysArray,
tokensDeposited: false,
tokensClaimed: 0,
exists: true
});
}
function getReserveAddresses(uint256 _pid) external view returns (address[] memory) {
return listReserveAddresses[_pid];
}
function tokensPurchaseAmt(uint256 _pid, address _tokenAdd, uint256 amt) public view returns (uint256) {
uint256 rateToken = saleRateInfo[_pid][_tokenAdd];
require(rateToken!=0, "NAT"); // NOT AVAILABLE TOKEN
return (amt.mul(1e18)).div(rateToken);
}
// Check if user can deposit specfic amount of funds to the pool
function _checkDepositAllowed(uint256 _pid, address _tokenAdd, uint256 _amt) internal view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
uint256 userBought = userTokenAllocation[_pid][_msgSender()];
uint256 purchasePossible = tokensPurchaseAmt(_pid, _tokenAdd, _amt);
require(pool.balanceAdded == true, "NA"); // NOT AVAILABLE
require(pool.startBlock <= block.number, "NT1"); // NOT AVAILABLE TIME 1
require(pool.endBlock >= block.number, "NT2"); // NOT AVAILABLE TIME 2
require(pool.totalTokensSold.add(purchasePossible) <= pool.totalTokensOnSale, "PLE"); // POOL LIMIT EXCEEDED
require(userBought.add(purchasePossible) <= pool.maxTokensPerPerson, "ILE"); // INDIVIDUAL LIMIT EXCEEDED
return purchasePossible;
}
// Check max a user can deposit right now
function getMaxDepositAllowed(uint256 _pid, address _tokenAdd, address _user) external view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
uint256 maxBuyPossible = (pool.maxTokensPerPerson).sub(userTokenAllocation[_pid][_user]);
uint256 maxBuyPossiblePoolLimit = (pool.totalTokensOnSale).sub(pool.totalTokensSold);
if(maxBuyPossiblePoolLimit < maxBuyPossible){
maxBuyPossible = maxBuyPossiblePoolLimit;
}
if(block.number >= pool.startBlock && block.number <= pool.endBlock && pool.balanceAdded == true){
uint256 rateToken = saleRateInfo[_pid][_tokenAdd];
return (maxBuyPossible.mul(rateToken).div(1e18));
}
else {
return 0;
}
}
// Check if deposit is enabled for a pool
function checkDepositEnabled(uint256 _pid) external view returns (bool){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.balanceAdded == true && pool.startBlock <= block.number && pool.endBlock >= block.number && pool.totalTokensSold <= pool.totalTokensOnSale && pool.paymentMethodAdded==true){
return true;
}
else {
return false;
}
}
// Deposit ICO tokens to start a pool for ICO.
function depositICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NOT"); // NOT VALID TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(block.number < pool.endBlock, "NT"); // No point adding tokens after sale has ended - Possible deadlock case
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
pool.tokensDeposited = (pool.tokensDeposited).add(_amount);
if(pool.tokensDeposited >= pool.totalTokensOnSale){
pool.balanceAdded = true;
}
emit Deposit(msgSender, _pid, _amount);
}
// Deposit Airdrop tokens anytime before end of the sale.
function depositAirdropTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.endBlock, "NT"); // NOT VALID TIME
AirdropPoolInfo storage airdrop = airdropInfo[_pid];
require((_tokenAdd == airdrop.airdropToken || airdrop.airdropExists==false), "NOT"); // NOT VALID TOKEN
require(_msgSender() == pool.owner || _msgSender() == devaddr , "NAU"); // NOT AUTHORISED USER
_tokenAdd.safeTransferFrom(_msgSender(), address(this), _amount);
airdrop.totalTokensAvailable = (airdrop.totalTokensAvailable).add(_amount);
if(!airdrop.airdropExists){
airdrop.airdropToken = _tokenAdd;
airdrop.airdropExists = true;
}
emit AirdropDeposit(_msgSender(), address(_tokenAdd), _pid, _amount);
}
// Withdraw extra airdrop tokens - Possible only if no one added liquidity to one of the pools
function withdrawExtraAirdropTokens(uint256 _pid) external {
require(extraAirdropClaimed[_pid]==false, "NA"); // NOT AVAILABLE
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "NSE"); // SALE NOT ENDED
address msgSender = _msgSender();
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
uint256 extraTokens = calculateExtraAirdropTokens(_pid);
require(extraTokens!=0, "NAT"); // NOT AVAILABLE TOKEN
extraAirdropClaimed[_pid] = true;
airdropInfo[_pid].airdropToken.safeTransfer(msgSender, extraTokens);
emit AirdropExtraWithdraw(msg.sender, address(airdropInfo[_pid].airdropToken), _pid, extraTokens);
}
function calculateExtraAirdropTokens(uint256 _pid) public view returns (uint256){
if(extraAirdropClaimed[_pid] == true) return 0;
uint256 _totalTokens;
for (uint256 i=0; i<stakingPools.length; i++){
uint256 stake = stakedLPTokensInfo[_pid][stakingPools[i]];
if(address(this).balance == 0){ //inject PRESENT ETHER
_totalTokens = _totalTokens.add(((stakingWeight[stakingPools[i]]).mul(airdropInfo[_pid].totalTokensAvailable)).div(totalStakeWeight));
}
}
return _totalTokens;
}
// Deposit LP tokens for a sale.
function stakeLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external {
require(stakingEnabled[address(_lpAdd)]==true, "NST"); // NOT STAKING TOKEN
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.startBlock, "NT"); // NOT VALID TIME
address msgSender = _msgSender();
_lpAdd.safeTransferFrom(msgSender, address(this), _amount);
stakedLPTokensInfo[_pid][address(_lpAdd)] = (stakedLPTokensInfo[_pid][address(_lpAdd)]).add(_amount);
userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).add(_amount);
emit Stake(msg.sender, address(_lpAdd), _pid, _amount);
}
// Withdraw LP tokens from a sale after it's over => Automatically claims rewards and airdrops also
function withdrawLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external {
require(stakingEnabled[address(_lpAdd)]==true, "NAT"); // NOT AUTHORISED TOKEN
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "SE"); // SALE NOT ENDED
address msgSender = _msgSender();
claimRewardAndAirdrop(_pid);
userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).sub(_amount);
_lpAdd.safeTransfer(msgSender, _amount);
emit UnStake(msg.sender, address(_lpAdd), _pid, _amount);
}
// Withdraw airdrop tokens accumulated over one or more than one sale.
function withdrawAirdropTokens(IERC20 _token, uint256 _amount) external {
address msgSender = _msgSender();
airdropBalances[address(_token)][msgSender] = (airdropBalances[address(_token)][msgSender]).sub(_amount);
_token.safeTransfer(msgSender, _amount);
emit WithdrawAirdrop(msgSender, address(_token), _amount);
}
// Move LP tokens from one sale to another directly => Automatically claims rewards and airdrops also
function moveLPTokens(uint256 _pid, uint256 _newpid, uint256 _amount, address _lpAdd) external {
require(stakingEnabled[_lpAdd]==true, "NAT1"); // NOT AUTHORISED TOKEN 1
RaisePoolInfo storage poolOld = poolInfo[_pid];
RaisePoolInfo storage poolNew = poolInfo[_newpid];
require(block.number > poolOld.endBlock, "NUA"); // OLD SALE NOT ENDED
require(block.number < poolNew.startBlock, "NSA"); // SALE START CHECK FAILED
address msgSender = _msgSender();
claimRewardAndAirdrop(_pid);
userStakeInfo[_pid][msgSender][_lpAdd] = (userStakeInfo[_pid][msgSender][_lpAdd]).sub(_amount);
userStakeInfo[_newpid][msgSender][_lpAdd] = (userStakeInfo[_newpid][msgSender][_lpAdd]).add(_amount);
emit MoveStake(msg.sender, _lpAdd, _pid, _newpid, _amount);
}
function claimRewardAndAirdrop(uint256 _pid) public {
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "SE"); // SUM INVALID
_claimReward(_pid, _msgSender());
_claimAirdrop(_pid, _msgSender());
}
function _claimReward(uint256 _pid, address _user) internal {
if (rewardClaimed[_pid][_user]==false){
rewardClaimed[_pid][_user] = true;
for (uint256 i=0; i<stakingPools.length; i++){
for(uint256 j=0; j<listSupportedCurrencies[_pid].length; j++){
uint256 _tokenAmt = getReward(_pid, _user, stakingPools[i], listSupportedCurrencies[_pid][j]);
_creditAirdrop(_user, listSupportedCurrencies[_pid][j], _tokenAmt);
}
}
}
}
function _claimAirdrop(uint256 _pid, address _user) internal {
if (airdropClaimed[_pid][_user]==false){
airdropClaimed[_pid][_user] = true;
address _airdropToken = address(airdropInfo[_pid].airdropToken);
uint256 _tokenAmt = 0;
for (uint256 i=0; i<stakingPools.length; i++){
_tokenAmt = _tokenAmt.add(getAirdrop(_pid, _user, stakingPools[i]));
}
if(_tokenAmt !=0){
_creditAirdrop(_user, _airdropToken, _tokenAmt);
}
}
}
function _creditAirdrop(address _user, address _token, uint256 _amt) internal {
airdropBalances[_token][_user] = (airdropBalances[_token][_user]).add(_amt);
emit ClaimAirdrop(_user, _token, _amt);
}
function getReward(uint256 _pid, address _user, address _lpAdd, address _token) public view returns (uint256) {
uint256 stake = stakedLPTokensInfo[_pid][_lpAdd];
if(address(this).balance==0) return 0; //inject PRESENT ETHER
uint256 _multipliedData = (userStakeInfo[_pid][_user][_lpAdd]).mul(fundsRaisedSoFar[_pid][_token]);
_multipliedData = (_multipliedData).mul(rewardPer).mul(fee).mul(stakingWeight[_lpAdd]);
return (((_multipliedData).div(stake)).div(1e8)).div(totalStakeWeight);
}
function getAirdrop(uint256 _pid, address _user, address _lpAdd) public view returns (uint256) {
uint256 _userStaked = userStakeInfo[_pid][_user][_lpAdd];
uint256 _totalStaked = stakedLPTokensInfo[_pid][_lpAdd];
if(address(this).balance==0) return 0; //inject PRESENT ETHER
return ((((_userStaked).mul(airdropInfo[_pid].totalTokensAvailable).mul(stakingWeight[_lpAdd])).div(_totalStaked))).div(totalStakeWeight);
}
// Deposit ICO tokens for a use case as reserve.
function depositReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd, address _resAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NOT"); // NOT AUTHORISED TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(poolU.tokensDeposited == false, "DR"); // TOKENS NOT DEPOSITED
require(poolU.tokensAllocated == _amount && _amount!=0, "NA"); // NOT AVAILABLE
require(block.number < pool.endBlock, "CRN"); // CANNOT_RESERVE_NOW to avoid deadlocks
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
totalTokenReserved[_pid] = (totalTokenReserved[_pid]).add(_amount);
poolU.tokensDeposited = true;
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw extra unsold ICO tokens or extra deposited tokens.
function withdrawExtraICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NT"); // NOT AUTHORISED TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(block.number > pool.endBlock, "NA"); // NOT AVAILABLE TIME
uint256 _amtAvail = pool.tokensDeposited.sub(pool.totalTokensSold);
require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE TOKEN
pool.tokensDeposited = (pool.tokensDeposited).sub(_amount);
_tokenAdd.safeTransfer(msgSender, _amount);
emit Withdraw(msgSender, _pid, _amount);
}
// Fetch extra ICO tokens available.
function fetchExtraICOTokens(uint256 _pid) external view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
return pool.tokensDeposited.sub(pool.totalTokensSold);
}
// Deposit tokens to a pool for ICO.
function deposit(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
address msgSender = _msgSender();
uint256 _buyThisStep = _checkDepositAllowed(_pid, address(_tokenAdd), _amount);
// require(_buyThisStep >= _amount, "CDE");
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
userDepositInfo[_pid][msgSender][address(_tokenAdd)] = userDepositInfo[_pid][msgSender][address(_tokenAdd)].add(_amount);
userTokenAllocation[_pid][msgSender] = userTokenAllocation[_pid][msgSender].add(_buyThisStep);
poolInfo[_pid].totalTokensSold = poolInfo[_pid].totalTokensSold.add(_buyThisStep);
fundsRaisedSoFar[_pid][address(_tokenAdd)] = fundsRaisedSoFar[_pid][address(_tokenAdd)].add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Vote your favourite ICO project.
function voteProject(uint256 _pid) external {
address msgSender = _msgSender();
require(userVotes[_pid][msgSender]==false,"AVO"); // ALREADY VOTED
require(poolInfo[_pid].endBlock >= block.number,"CVO"); // CANNOT VOTE NOW
userVotes[_pid][msgSender] = true;
poolInfo[_pid].votes = (poolInfo[_pid].votes).add(1);
emit Voted(msgSender, _pid);
}
function _calculatePerAvailable(uint256[] memory _daysArray, uint256[] memory _percentArray, uint256 blockEnd) internal view returns (uint256) {
uint256 _defaultPer = 10000;
uint256 _perNow;
if(address(this).balance==0){ //inject PRESENT ETHER
return _defaultPer;
}
uint256 daysDone = ((block.number).sub(blockEnd)).div(BLOCKS_PER_DAY);
for (uint256 i = 0; i < _daysArray.length; i++) {
if(_daysArray[i] <= daysDone){
_perNow = _perNow.add(_percentArray[i]);
}
else {
break;
}
}
return _perNow;
}
function _getPercentAvailable(uint256 _pid, uint256 blockEnd) internal view returns (uint256){
DistributionInfo storage distInfo = userDistInfo[_pid];
uint256[] storage _percentArray = distInfo.percentArray;
uint256[] storage _daysArray = distInfo.daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by user till now - public
function amountAvailToWithdrawUser(uint256 _pid, address _user) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailable(_pid, pool.endBlock);
return ((percentAvail).mul(userTokenAllocation[_pid][_user]).div(10000)).sub(userTokenClaimed[_pid][_user]);
}
else {
return 0;
}
}
// Withdraw ICO tokens after sale is over based on distribution rules.
function withdrawUser(uint256 _pid, uint256 _amount) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
uint256 _amtAvail = amountAvailToWithdrawUser(_pid, msgSender);
require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN
userTokenClaimed[_pid][msgSender] = userTokenClaimed[_pid][msgSender].add(_amount);
totalTokenClaimed[_pid] = totalTokenClaimed[_pid].add(_amount);
pool.raiseToken.safeTransfer(msgSender, _amount);
emit Withdraw(msgSender, _pid, _amount);
}
function _getPercentAvailableFundRaiser(uint256 _pid, uint256 blockEnd) internal view returns (uint256){
DistributionInfo storage distInfo = ownerDistInfo[_pid];
uint256[] storage _percentArray = distInfo.percentArray;
uint256[] storage _daysArray = distInfo.daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by user till now
function amountAvailToWithdrawFundRaiser(uint256 _pid, IERC20 _tokenAdd) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailableFundRaiser(_pid, pool.endBlock);
return (((percentAvail).mul(fundsRaisedSoFar[_pid][address(_tokenAdd)]).div(10000))).sub(fundsClaimedSoFar[_pid][address(_tokenAdd)]);
}
else {
return 0;
}
}
function _getPercentAvailableReserve(uint256 _pid, uint256 blockEnd, address _resAdd) internal view returns (uint256){
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
uint256[] storage _percentArray = poolU.unlock_perArray;
uint256[] storage _daysArray = poolU.unlock_daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by reserve user till now
function amountAvailToWithdrawReserve(uint256 _pid, address _resAdd) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailableReserve(_pid, pool.endBlock, _resAdd);
return ((percentAvail).mul(poolU.tokensAllocated).div(10000)).sub(poolU.tokensClaimed);
}
else {
return 0;
}
}
// Withdraw ICO tokens for various use cases as per the schedule promised on provided address.
function withdrawReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_msgSender()];
require(poolU.reserveAdd == _msgSender(), "NAUTH"); // NOT AUTHORISED USER
require(_tokenAdd == poolInfo[_pid].raiseToken, "NT"); // NOT AUTHORISED TOKEN
uint256 _amtAvail = amountAvailToWithdrawReserve(_pid, _msgSender());
require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE USER
poolU.tokensClaimed = poolU.tokensClaimed.add(_amount);
totalTokenReserved[_pid] = totalTokenReserved[_pid].sub(_amount);
totalReservedTokenClaimed[_pid] = totalReservedTokenClaimed[_pid].add(_amount);
_tokenAdd.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _pid, _amount);
}
// Withdraw raised funds after sale is over as per the schedule promised
function withdrawFundRaiser(uint256 _pid, uint256 _amount, IERC20 _tokenAddress) external {
RaisePoolInfo storage pool = poolInfo[_pid];
require(pool.owner == _msgSender(), "NAUTH"); // NOT AUTHORISED USER
uint256 _amtAvail = amountAvailToWithdrawFundRaiser(_pid, _tokenAddress);
require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN
uint256 _fee = ((_amount).mul(fee)).div(1e4);
uint256 _actualTransfer = _amtAvail.sub(_fee);
uint256 _feeDev = (_fee).mul(10000 - rewardPer).div(1e4); // Remaining tokens for reward mining
fundsClaimedSoFar[_pid][address(_tokenAddress)] = fundsClaimedSoFar[_pid][address(_tokenAddress)].add(_amount);
_tokenAddress.safeTransfer(_msgSender(), _actualTransfer);
_tokenAddress.safeTransfer(devaddr, _feeDev);
emit Withdraw(_msgSender(), _pid, _actualTransfer);
emit Withdraw(devaddr, _pid, _feeDev);
}
// Update dev address by initiating with the previous dev.
function changeDev(address _newowner) external onlyAdmin {
potentialAdmin = _newowner;
}
function becomeDev() external {
require(potentialAdmin == msg.sender, "NA"); // NOT ALLOWED
devaddr = msg.sender;
}
// Update temp pool owner address by initiating with the previous pool owner.
function changePoolOwner(uint256 _pid, address _newowner) external {
require(_msgSender()==poolInfo[_pid].owner, "OA"); // NOT AUTHORISED USER
tempAdmin[_pid] = _newowner;
}
// Claim pool ownership with new address
function becomePoolOwner(uint256 _pid) external {
if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender();
}
// Update fee, can never be more than 3%.
function changeFee(uint256 _fee) external onlyAdmin{
require(_fee <= 300, "MAX3"); // MAX FEE POSSIBLE
fee = _fee;
}
// To generate a new invite code
function generateNewCode(address _token, address _poolOwner) external onlyAdminOrTimeLock returns (uint256) {
uint256 inviteCode = block.number;
inviteCodeList[inviteCode][_token][_poolOwner] = true;
return inviteCode;
}
// To invalidate an invite code
function invalidateOldCode(uint256 _inviteCode, address _token, address _poolOwner) external onlyAdmin {
inviteCodeList[_inviteCode][_token][_poolOwner] = false;
}
// To add or update a staking pool with weight
function addStakingPool(address _token, uint256 _weight) external onlyAdmin {
if(stakingEnabled[_token]==false){
stakingPools.push(_token);
stakingEnabled[_token] = true;
}
totalStakeWeight = totalStakeWeight.sub(stakingWeight[_token]).add(_weight);
stakingWeight[_token] = _weight;
}
}
|
Add supported currencies and their rate w.r.t token on sale rateToken = price of one satoshi of the token in terms of token to be raised 1e18 1 BNSD = 0.00021 ETH => 1e18 BNSD Satoshi = 0.00021 1e18 ETH satoshi => 1 BNSD Satoshi = 0.00021 ETH satoshi => rateToken = 0.00021 1e18 = 21 1e13 rateToken for BNSD/ETH pair = 21 1e13;
|
function addSupportedCurrencies(uint256 _pid, address _tokenRaise, uint256 rateToken) external {
_checkUpdateAllowed(_pid);
listSupportedCurrencies[_pid].push(_tokenRaise);
}
saleRateInfo[_pid][_tokenRaise] = rateToken;
poolInfo[_pid].paymentMethodAdded = true;
| 1,045,274 |
./partial_match/1/0x41C1F38A4BbFA4f14Ef235ed8901b3a0e51a2933/sources/NABC.sol
|
Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
|
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(
_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue
);
return true;
}
| 2,617,104 |
pragma solidity ^0.4.24;
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncSend instead of send or transfer.
*/
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev Withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(address(this).balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
payee.transfer(payment);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract CryptoMiningWar is PullPayment {
bool public initialized = false;
uint256 public roundNumber = 0;
uint256 public deadline;
uint256 public CRTSTAL_MINING_PERIOD = 86400;
uint256 public HALF_TIME = 8 hours;
uint256 public ROUND_TIME = 86400 * 7;
uint256 public prizePool = 0;
uint256 BASE_PRICE = 0.005 ether;
uint256 RANK_LIST_LIMIT = 10000;
uint256 MINIMUM_LIMIT_SELL = 5000000;
uint256 randNonce = 0;
//miner info
mapping(uint256 => MinerData) private minerData;
uint256 private numberOfMiners;
// plyer info
mapping(address => PlayerData) private players;
//booster info
uint256 private numberOfBoosts;
mapping(uint256 => BoostData) private boostData;
//order info
uint256 private numberOfOrders;
mapping(uint256 => BuyOrderData) private buyOrderData;
mapping(uint256 => SellOrderData) private sellOrderData;
uint256 private numberOfRank;
address[21] rankList;
address public sponsor;
uint256 public sponsorLevel;
address public administrator;
/*** DATATYPES ***/
struct PlayerData {
uint256 roundNumber;
mapping(uint256 => uint256) minerCount;
uint256 hashrate;
uint256 crystals;
uint256 lastUpdateTime;
uint256 referral_count;
uint256 noQuest;
}
struct MinerData {
uint256 basePrice;
uint256 baseProduct;
uint256 limit;
}
struct BoostData {
address owner;
uint256 boostRate;
uint256 startingLevel;
uint256 startingTime;
uint256 halfLife;
}
struct BuyOrderData {
address owner;
string title;
string description;
uint256 unitPrice;
uint256 amount;
}
struct SellOrderData {
address owner;
string title;
string description;
uint256 unitPrice;
uint256 amount;
}
event eventDoQuest(
uint clientNumber,
uint randomNumber
);
modifier isNotOver()
{
require(now <= deadline);
_;
}
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
modifier isCurrentRound()
{
require(players[msg.sender].roundNumber == roundNumber);
_;
}
modifier limitSell()
{
PlayerData storage p = players[msg.sender];
if(p.hashrate <= MINIMUM_LIMIT_SELL){
_;
}else{
uint256 limit_hashrate = 0;
if(rankList[9] != 0){
PlayerData storage rank_player = players[rankList[9]];
limit_hashrate = SafeMath.mul(rank_player.hashrate, 5);
}
require(p.hashrate <= limit_hashrate);
_;
}
}
constructor() public {
administrator = msg.sender;
numberOfMiners = 8;
numberOfBoosts = 5;
numberOfOrders = 5;
numberOfRank = 21;
//init miner data
// price, prod. limit
minerData[0] = MinerData(10, 10, 10); //lv1
minerData[1] = MinerData(100, 200, 2); //lv2
minerData[2] = MinerData(400, 800, 4); //lv3
minerData[3] = MinerData(1600, 3200, 8); //lv4
minerData[4] = MinerData(6400, 9600, 16); //lv5
minerData[5] = MinerData(25600, 38400, 32); //lv6
minerData[6] = MinerData(204800, 204800, 64); //lv7
minerData[7] = MinerData(1638400, 819200, 65536); //lv8
}
function () public payable
{
prizePool = SafeMath.add(prizePool, msg.value);
}
function startGame() public
{
require(msg.sender == administrator);
require(!initialized);
startNewRound();
initialized = true;
}
function startNewRound() private
{
deadline = SafeMath.add(now, ROUND_TIME);
roundNumber = SafeMath.add(roundNumber, 1);
initData();
}
function initData() private
{
sponsor = administrator;
sponsorLevel = 6;
//init booster data
boostData[0] = BoostData(0, 150, 1, now, HALF_TIME);
boostData[1] = BoostData(0, 175, 1, now, HALF_TIME);
boostData[2] = BoostData(0, 200, 1, now, HALF_TIME);
boostData[3] = BoostData(0, 225, 1, now, HALF_TIME);
boostData[4] = BoostData(msg.sender, 250, 2, now, HALF_TIME);
//init order data
uint256 idx;
for (idx = 0; idx < numberOfOrders; idx++) {
buyOrderData[idx] = BuyOrderData(0, "title", "description", 0, 0);
sellOrderData[idx] = SellOrderData(0, "title", "description", 0, 0);
}
for (idx = 0; idx < numberOfRank; idx++) {
rankList[idx] = 0;
}
}
function lottery() public disableContract
{
require(now > deadline);
uint256 balance = SafeMath.div(SafeMath.mul(prizePool, 90), 100);
uint256 devFee = SafeMath.div(SafeMath.mul(prizePool, 5), 100);
asyncSend(administrator, devFee);
uint8[10] memory profit = [30,20,10,8,7,5,5,5,5,5];
uint256 totalPayment = 0;
uint256 rankPayment = 0;
for(uint256 idx = 0; idx < 10; idx++){
if(rankList[idx] != 0){
rankPayment = SafeMath.div(SafeMath.mul(balance, profit[idx]),100);
asyncSend(rankList[idx], rankPayment);
totalPayment = SafeMath.add(totalPayment, rankPayment);
}
}
prizePool = SafeMath.add(devFee, SafeMath.sub(balance, totalPayment));
startNewRound();
}
function getRankList() public view returns(address[21])
{
return rankList;
}
//sponser
function becomeSponsor() public isNotOver payable
{
require(msg.value >= getSponsorFee());
require(msg.sender != sponsor);
uint256 sponsorPrice = getCurrentPrice(sponsorLevel);
asyncSend(sponsor, sponsorPrice);
prizePool = SafeMath.add(prizePool, SafeMath.sub(msg.value, sponsorPrice));
sponsor = msg.sender;
sponsorLevel = SafeMath.add(sponsorLevel, 1);
}
function getSponsorFee() public view returns(uint256 sponsorFee)
{
sponsorFee = getCurrentPrice(SafeMath.add(sponsorLevel, 1));
}
//--------------------------------------------------------------------------
// Miner
//--------------------------------------------------------------------------
function getFreeMiner(address ref) public disableContract isNotOver
{
require(players[msg.sender].roundNumber != roundNumber);
PlayerData storage p = players[msg.sender];
//reset player data
if(p.hashrate > 0){
for (uint idx = 1; idx < numberOfMiners; idx++) {
p.minerCount[idx] = 0;
}
}
p.crystals = 0;
p.roundNumber = roundNumber;
//free miner
p.lastUpdateTime = now;
p.referral_count = 0;
p.noQuest = 0;
p.minerCount[0] = 1;
MinerData storage m0 = minerData[0];
p.hashrate = m0.baseProduct;
}
function doQuest(uint256 clientNumber) disableContract isCurrentRound isNotOver public
{
PlayerData storage p = players[msg.sender];
p.noQuest = SafeMath.add(p.noQuest, 1);
uint256 randomNumber = getRandomNumber(msg.sender);
if(clientNumber == randomNumber) {
p.referral_count = SafeMath.add(p.referral_count, 1);
}
emit eventDoQuest(clientNumber, randomNumber);
}
function buyMiner(uint256[] minerNumbers) public isNotOver isCurrentRound
{
require(minerNumbers.length == numberOfMiners);
uint256 minerIdx = 0;
MinerData memory m;
for (; minerIdx < numberOfMiners; minerIdx++) {
m = minerData[minerIdx];
if(minerNumbers[minerIdx] > m.limit || minerNumbers[minerIdx] < 0){
revert();
}
}
updateCrytal(msg.sender);
PlayerData storage p = players[msg.sender];
uint256 price = 0;
uint256 minerNumber = 0;
for (minerIdx = 0; minerIdx < numberOfMiners; minerIdx++) {
minerNumber = minerNumbers[minerIdx];
if (minerNumber > 0) {
m = minerData[minerIdx];
price = SafeMath.add(price, SafeMath.mul(m.basePrice, minerNumber));
}
}
price = SafeMath.mul(price, CRTSTAL_MINING_PERIOD);
if(p.crystals < price){
revert();
}
for (minerIdx = 0; minerIdx < numberOfMiners; minerIdx++) {
minerNumber = minerNumbers[minerIdx];
if (minerNumber > 0) {
m = minerData[minerIdx];
p.minerCount[minerIdx] = SafeMath.min(m.limit, SafeMath.add(p.minerCount[minerIdx], minerNumber));
}
}
p.crystals = SafeMath.sub(p.crystals, price);
updateHashrate(msg.sender);
}
function getPlayerData(address addr) public view
returns (uint256 crystals, uint256 lastupdate, uint256 hashratePerDay, uint256[8] miners, uint256 hasBoost, uint256 referral_count, uint256 playerBalance, uint256 noQuest )
{
PlayerData storage p = players[addr];
if(p.roundNumber != roundNumber){
p = players[0];
}
crystals = SafeMath.div(p.crystals, CRTSTAL_MINING_PERIOD);
lastupdate = p.lastUpdateTime;
hashratePerDay = addReferralHashrate(addr, p.hashrate);
uint256 i = 0;
for(i = 0; i < numberOfMiners; i++)
{
miners[i] = p.minerCount[i];
}
hasBoost = hasBooster(addr);
referral_count = p.referral_count;
noQuest = p.noQuest;
playerBalance = payments[addr];
}
function getHashratePerDay(address minerAddr) public view returns (uint256 personalProduction)
{
PlayerData storage p = players[minerAddr];
personalProduction = addReferralHashrate(minerAddr, p.hashrate);
uint256 boosterIdx = hasBooster(minerAddr);
if (boosterIdx != 999) {
BoostData storage b = boostData[boosterIdx];
personalProduction = SafeMath.div(SafeMath.mul(personalProduction, b.boostRate), 100);
}
}
//--------------------------------------------------------------------------
// BOOSTER
//--------------------------------------------------------------------------
function buyBooster(uint256 idx) public isNotOver isCurrentRound payable
{
require(idx < numberOfBoosts);
BoostData storage b = boostData[idx];
if(msg.value < getBoosterPrice(idx) || msg.sender == b.owner){
revert();
}
address beneficiary = b.owner;
uint256 devFeePrize = devFee(getBoosterPrice(idx));
asyncSend(sponsor, devFeePrize);
uint256 refundPrize = 0;
if(beneficiary != 0){
refundPrize = SafeMath.div(SafeMath.mul(getBoosterPrice(idx), 55), 100);
asyncSend(beneficiary, refundPrize);
}
prizePool = SafeMath.add(prizePool, SafeMath.sub(msg.value, SafeMath.add(devFeePrize, refundPrize)));
updateCrytal(msg.sender);
updateCrytal(beneficiary);
uint256 level = getCurrentLevel(b.startingLevel, b.startingTime, b.halfLife);
b.startingLevel = SafeMath.add(level, 1);
b.startingTime = now;
// transfer ownership
b.owner = msg.sender;
}
function getBoosterData(uint256 idx) public view returns (address owner,uint256 boostRate, uint256 startingLevel,
uint256 startingTime, uint256 currentPrice, uint256 halfLife)
{
require(idx < numberOfBoosts);
owner = boostData[idx].owner;
boostRate = boostData[idx].boostRate;
startingLevel = boostData[idx].startingLevel;
startingTime = boostData[idx].startingTime;
currentPrice = getBoosterPrice(idx);
halfLife = boostData[idx].halfLife;
}
function getBoosterPrice(uint256 index) public view returns (uint256)
{
BoostData storage booster = boostData[index];
return getCurrentPrice(getCurrentLevel(booster.startingLevel, booster.startingTime, booster.halfLife));
}
function hasBooster(address addr) public view returns (uint256 boostIdx)
{
boostIdx = 999;
for(uint256 i = 0; i < numberOfBoosts; i++){
uint256 revert_i = numberOfBoosts - i - 1;
if(boostData[revert_i].owner == addr){
boostIdx = revert_i;
break;
}
}
}
//--------------------------------------------------------------------------
// Market
//--------------------------------------------------------------------------
function buyCrystalDemand(uint256 amount, uint256 unitPrice,string title, string description) public isNotOver isCurrentRound payable
{
require(unitPrice >= 100000000000);
require(amount >= 1000);
require(SafeMath.mul(amount, unitPrice) <= msg.value);
uint256 lowestIdx = getLowestUnitPriceIdxFromBuy();
BuyOrderData storage o = buyOrderData[lowestIdx];
if(o.amount > 10 && unitPrice <= o.unitPrice){
revert();
}
uint256 balance = SafeMath.mul(o.amount, o.unitPrice);
if (o.owner != 0){
asyncSend(o.owner, balance);
}
o.owner = msg.sender;
o.unitPrice = unitPrice;
o.title = title;
o.description = description;
o.amount = amount;
}
function sellCrystal(uint256 amount, uint256 index) public isNotOver isCurrentRound limitSell
{
require(index < numberOfOrders);
require(amount > 0);
BuyOrderData storage o = buyOrderData[index];
require(o.owner != msg.sender);
require(amount <= o.amount);
updateCrytal(msg.sender);
PlayerData storage seller = players[msg.sender];
PlayerData storage buyer = players[o.owner];
require(seller.crystals >= SafeMath.mul(amount, CRTSTAL_MINING_PERIOD));
uint256 price = SafeMath.mul(amount, o.unitPrice);
uint256 fee = devFee(price);
asyncSend(sponsor, fee);
asyncSend(administrator, fee);
prizePool = SafeMath.add(prizePool, SafeMath.div(SafeMath.mul(price, 40), 100));
buyer.crystals = SafeMath.add(buyer.crystals, SafeMath.mul(amount, CRTSTAL_MINING_PERIOD));
seller.crystals = SafeMath.sub(seller.crystals, SafeMath.mul(amount, CRTSTAL_MINING_PERIOD));
o.amount = SafeMath.sub(o.amount, amount);
asyncSend(msg.sender, SafeMath.div(price, 2));
}
function withdrawBuyDemand(uint256 index) public isNotOver isCurrentRound
{
require(index < numberOfOrders);
BuyOrderData storage o = buyOrderData[index];
require(o.owner == msg.sender);
if(o.amount > 0){
uint256 balance = SafeMath.mul(o.amount, o.unitPrice);
asyncSend(o.owner, balance);
}
o.unitPrice = 0;
o.amount = 0;
o.title = "title";
o.description = "description";
o.owner = 0;
}
function getBuyDemand(uint256 index) public view returns(address owner, string title, string description,
uint256 amount, uint256 unitPrice)
{
require(index < numberOfOrders);
BuyOrderData storage o = buyOrderData[index];
owner = o.owner;
title = o.title;
description = o.description;
amount = o.amount;
unitPrice = o.unitPrice;
}
function getLowestUnitPriceIdxFromBuy() public view returns(uint256 lowestIdx)
{
uint256 lowestPrice = 2**256 - 1;
for (uint256 idx = 0; idx < numberOfOrders; idx++) {
BuyOrderData storage o = buyOrderData[idx];
//if empty
if (o.unitPrice == 0 || o.amount < 10) {
return idx;
}else if (o.unitPrice < lowestPrice) {
lowestPrice = o.unitPrice;
lowestIdx = idx;
}
}
}
//-------------------------Sell-----------------------------
function sellCrystalDemand(uint256 amount, uint256 unitPrice, string title, string description)
public isNotOver isCurrentRound limitSell
{
require(amount >= 1000);
updateCrytal(msg.sender);
PlayerData storage seller = players[msg.sender];
if(seller.crystals < SafeMath.mul(amount, CRTSTAL_MINING_PERIOD)){
revert();
}
uint256 highestIdx = getHighestUnitPriceIdxFromSell();
SellOrderData storage o = sellOrderData[highestIdx];
if(o.amount > 10 && unitPrice >= o.unitPrice){
revert();
}
if (o.owner != 0){
PlayerData storage prev = players[o.owner];
prev.crystals = SafeMath.add(prev.crystals, SafeMath.mul(o.amount, CRTSTAL_MINING_PERIOD));
}
o.owner = msg.sender;
o.unitPrice = unitPrice;
o.title = title;
o.description = description;
o.amount = amount;
//sub crystals
seller.crystals = SafeMath.sub(seller.crystals, SafeMath.mul(amount, CRTSTAL_MINING_PERIOD));
}
function buyCrystal(uint256 amount, uint256 index) public isNotOver isCurrentRound payable
{
require(index < numberOfOrders);
require(amount > 0);
SellOrderData storage o = sellOrderData[index];
require(o.owner != msg.sender);
require(amount <= o.amount);
uint256 price = SafeMath.mul(amount, o.unitPrice);
require(msg.value >= price);
PlayerData storage buyer = players[msg.sender];
uint256 fee = devFee(price);
asyncSend(sponsor, fee);
asyncSend(administrator, fee);
prizePool = SafeMath.add(prizePool, SafeMath.div(SafeMath.mul(price, 40), 100));
buyer.crystals = SafeMath.add(buyer.crystals, SafeMath.mul(amount, CRTSTAL_MINING_PERIOD));
o.amount = SafeMath.sub(o.amount, amount);
asyncSend(o.owner, SafeMath.div(price, 2));
}
function withdrawSellDemand(uint256 index) public isNotOver isCurrentRound
{
require(index < numberOfOrders);
SellOrderData storage o = sellOrderData[index];
require(o.owner == msg.sender);
if(o.amount > 0){
PlayerData storage p = players[o.owner];
p.crystals = SafeMath.add(p.crystals, SafeMath.mul(o.amount, CRTSTAL_MINING_PERIOD));
}
o.unitPrice = 0;
o.amount = 0;
o.title = "title";
o.description = "description";
o.owner = 0;
}
function getSellDemand(uint256 index) public view returns(address owner, string title, string description,
uint256 amount, uint256 unitPrice)
{
require(index < numberOfOrders);
SellOrderData storage o = sellOrderData[index];
owner = o.owner;
title = o.title;
description = o.description;
amount = o.amount;
unitPrice = o.unitPrice;
}
function getHighestUnitPriceIdxFromSell() public view returns(uint256 highestIdx)
{
uint256 highestPrice = 0;
for (uint256 idx = 0; idx < numberOfOrders; idx++) {
SellOrderData storage o = sellOrderData[idx];
//if empty
if (o.unitPrice == 0 || o.amount < 10) {
return idx;
}else if (o.unitPrice > highestPrice) {
highestPrice = o.unitPrice;
highestIdx = idx;
}
}
}
//--------------------------------------------------------------------------
// Other
//--------------------------------------------------------------------------
function devFee(uint256 amount) public pure returns(uint256)
{
return SafeMath.div(SafeMath.mul(amount, 5), 100);
}
function getBalance() public view returns(uint256)
{
return address(this).balance;
}
//@dev use this function in case of bug
function upgrade(address addr) public
{
require(msg.sender == administrator);
selfdestruct(addr);
}
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
function updateHashrate(address addr) private
{
PlayerData storage p = players[addr];
uint256 hashrate = 0;
for (uint idx = 0; idx < numberOfMiners; idx++) {
MinerData storage m = minerData[idx];
hashrate = SafeMath.add(hashrate, SafeMath.mul(p.minerCount[idx], m.baseProduct));
}
p.hashrate = hashrate;
if(hashrate > RANK_LIST_LIMIT){
updateRankList(addr);
}
}
function updateCrytal(address addr) private
{
require(now > players[addr].lastUpdateTime);
if (players[addr].lastUpdateTime != 0) {
PlayerData storage p = players[addr];
uint256 secondsPassed = SafeMath.sub(now, p.lastUpdateTime);
uint256 revenue = getHashratePerDay(addr);
p.lastUpdateTime = now;
if (revenue > 0) {
revenue = SafeMath.mul(revenue, secondsPassed);
p.crystals = SafeMath.add(p.crystals, revenue);
}
}
}
function addReferralHashrate(address addr, uint256 hashrate) private view returns(uint256 personalProduction)
{
PlayerData storage p = players[addr];
if(p.referral_count < 5){
personalProduction = SafeMath.add(hashrate, SafeMath.mul(p.referral_count, 10));
}else if(p.referral_count < 10){
personalProduction = SafeMath.add(hashrate, SafeMath.add(50, SafeMath.mul(p.referral_count, 10)));
}else{
personalProduction = SafeMath.add(hashrate, 200);
}
}
function getCurrentLevel(uint256 startingLevel, uint256 startingTime, uint256 halfLife) private view returns(uint256)
{
uint256 timePassed=SafeMath.sub(now, startingTime);
uint256 levelsPassed=SafeMath.div(timePassed, halfLife);
if (startingLevel < levelsPassed) {
return 0;
}
return SafeMath.sub(startingLevel, levelsPassed);
}
function getCurrentPrice(uint256 currentLevel) private view returns(uint256)
{
return SafeMath.mul(BASE_PRICE, 2**currentLevel);
}
function updateRankList(address addr) private returns(bool)
{
uint256 idx = 0;
PlayerData storage insert = players[addr];
PlayerData storage lastOne = players[rankList[19]];
if(insert.hashrate < lastOne.hashrate) {
return false;
}
address[21] memory tempList = rankList;
if(!inRankList(addr)){
tempList[20] = addr;
quickSort(tempList, 0, 20);
}else{
quickSort(tempList, 0, 19);
}
for(idx = 0;idx < 21; idx++){
if(tempList[idx] != rankList[idx]){
rankList[idx] = tempList[idx];
}
}
return true;
}
function inRankList(address addr) internal view returns(bool)
{
for(uint256 idx = 0;idx < 20; idx++){
if(addr == rankList[idx]){
return true;
}
}
return false;
}
function getRandomNumber(address playerAddress) internal returns(uint256 randomNumber) {
randNonce++;
randomNumber = uint256(keccak256(now, playerAddress, randNonce)) % 3;
}
function quickSort(address[21] list, int left, int right) internal
{
int i = left;
int j = right;
if(i == j) return;
address addr = list[uint(left + (right - left) / 2)];
PlayerData storage p = players[addr];
while (i <= j) {
while (players[list[uint(i)]].hashrate > p.hashrate) i++;
while (p.hashrate > players[list[uint(j)]].hashrate) j--;
if (i <= j) {
(list[uint(i)], list[uint(j)]) = (list[uint(j)], list[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(list, left, j);
if (i < right)
quickSort(list, i, right);
}
}
|
-------------------------------------------------------------------------- BOOSTER--------------------------------------------------------------------------
|
function buyBooster(uint256 idx) public isNotOver isCurrentRound payable
{
require(idx < numberOfBoosts);
BoostData storage b = boostData[idx];
if(msg.value < getBoosterPrice(idx) || msg.sender == b.owner){
revert();
}
address beneficiary = b.owner;
uint256 devFeePrize = devFee(getBoosterPrice(idx));
asyncSend(sponsor, devFeePrize);
uint256 refundPrize = 0;
if(beneficiary != 0){
refundPrize = SafeMath.div(SafeMath.mul(getBoosterPrice(idx), 55), 100);
asyncSend(beneficiary, refundPrize);
}
prizePool = SafeMath.add(prizePool, SafeMath.sub(msg.value, SafeMath.add(devFeePrize, refundPrize)));
updateCrytal(msg.sender);
updateCrytal(beneficiary);
uint256 level = getCurrentLevel(b.startingLevel, b.startingTime, b.halfLife);
b.startingLevel = SafeMath.add(level, 1);
b.startingTime = now;
}
| 7,869,590 |
./full_match/5/0x4a10c90C0A6616e98336BBc5C521c628FA1Ed663/sources/contracts/contracts-v10/contracts/CheckerMaster.sol
|
Tasks --------------------
|
function requireWorkerOnTask(
uint256 _taskID,
address _address
) public view {
require(
isWorkerOnTask(_taskID, _address),
"Address is not worker on task"
);
}
| 11,586,439 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
/**
* @notice Simple multi-sig Wallet.
*/
contract Wallet {
bool isInit;
uint256 public threshold;
uint256 private transactionIndex;
uint256 private updatethresholdIndex;
uint256 private removeOwnerIndex;
uint256 private addOwnerIndex;
address[] public owners;
mapping(address => bool) isOwner;
mapping(address => mapping(uint256 => bool)) transactionSigners;
mapping(address => mapping(uint256 => bool)) updatethresholdSigners;
mapping(address => mapping(uint256 => bool)) removeOwnerSigners;
mapping(address => mapping(uint256 => bool)) addOwnerSigners;
event NewTransaction(address to, uint256 value, address sender);
event NewDeposit(address _sender, uint256 _value);
event NewThreshold(
uint256 oldThreshold,
uint256 newthreshold,
address sender
);
event OwnerRemoved(address removed, address sender);
event OwnerAdded(address newOwner, address sender);
struct Transaction {
address to;
uint256 value;
uint256 index;
uint256 signatures;
bool approved;
}
struct UpdateThreshold {
uint256 threshold;
uint256 index;
uint256 signatures;
bool approved;
}
struct RemoveOwner {
address remove;
uint256 index;
uint256 signatures;
bool approved;
}
struct AddOwner {
address add;
uint256 index;
uint256 signatures;
bool approved;
}
Transaction[] transactions;
UpdateThreshold[] updatethreshold;
RemoveOwner[] removeOwner;
AddOwner[] addOwner;
constructor(address[] memory _owners, uint256 _threshold) {
require(!isInit, "wallet in use");
require(_owners.length > 0, "There needs to be more than 0 owners");
require(_threshold <= _owners.length, "threshold exceeds owners");
require(_threshold > 0, "threshold needs to be more than 0");
for (uint256 i = 0; i < _owners.length; i++) {
address owner = _owners[i];
require(!isOwner[owner], "Address already an owner");
require(owner != address(this), "This address can't be owner");
require(owner != address(0), "Address 0 can't be owner");
owners.push(owner);
isOwner[owner] = true;
}
threshold = _threshold;
isInit = true;
}
receive() external payable {
emit NewDeposit(msg.sender, msg.value);
}
// checks if the caller is an owner.
modifier onlyOwners() {
require(isOwner[msg.sender], "Not owner");
_;
}
/**
* @notice creates a transaction request and adds one signature.
* @param _to - receiver of the transaction.
* @param _value - amount in WEI.
*/
function transactionRequest(address _to, uint256 _value)
external
onlyOwners
{
require(address(this).balance >= _value, "Not enough funds");
require(_to != address(0), "address zero not supported");
require(_value > 0, "Value cannot be 0");
transactions.push(
Transaction({
to: _to,
value: _value,
index: transactionIndex,
signatures: 0,
approved: false
})
);
transactionIndex += 1;
}
/**
* @notice approves a transaction after reaching the threshold
* @param _index index of the transaction.
*/
function transactionApproval(uint256 _index) external onlyOwners {
require(transactions[_index].value >= 0, "Transaction does not exists");
require(
transactionSigners[msg.sender][_index] == false,
"You already signed this transaction"
);
Transaction storage t = transactions[_index];
require(!t.approved, "Transaction already approved");
t.signatures += 1;
transactionSigners[msg.sender][_index] = true;
if (t.signatures >= threshold) {
(bool sent, ) = t.to.call{value: t.value}("");
require(sent, "Transaction failed");
t.approved = true;
emit NewTransaction(t.to, t.value, msg.sender);
}
}
/**
* @notice creates a request to update the threshold and adds a signature.
* @param _newThreshold the new threshold.
*/
function updatethresholdRequest(uint256 _newThreshold) external onlyOwners {
require(
_newThreshold <= totalOwners(),
"threshold exceeds total owners"
);
require(_newThreshold > 0, "You need at least threshold of 1");
updatethreshold.push(
UpdateThreshold({
threshold: _newThreshold,
index: updatethresholdIndex,
signatures: 0,
approved: false
})
);
updatethresholdIndex += 1;
}
/**
* @notice updates the threshold after reaching the threshold.
* @param _index transaction index.
*/
function updatethresholdApproval(uint256 _index) external onlyOwners {
require(
updatethreshold[_index].threshold > 0,
"Transaction does not exists"
);
require(
updatethresholdSigners[msg.sender][_index] == false,
"Owner already signed this transaction"
);
UpdateThreshold storage uq = updatethreshold[_index];
require(!uq.approved, "Transaction already approved");
uq.signatures += 1;
updatethresholdSigners[msg.sender][_index] = true;
if (uq.signatures >= threshold) {
emit NewThreshold(threshold, uq.threshold, msg.sender);
threshold = uq.threshold;
uq.approved = true;
}
}
/**
* @notice request to remove an owner.
* @param _remove the owner to remove.
*/
function removeOwnerRequest(address _remove) external onlyOwners {
require(isOwner[_remove], "Address is not an owner");
require((totalOwners() - 1) > 0, "There needs to be at least 1 owner");
require(
(totalOwners() - 1) >= threshold,
"There needs to be more owners than threshold"
);
removeOwner.push(
RemoveOwner({
remove: _remove,
index: removeOwnerIndex,
signatures: 0,
approved: false
})
);
removeOwnerIndex += 1;
}
/**
* @notice removes an owner after reaching the threshold.
* @param _index the transaction index.
*/
function removeOwnerApproval(uint256 _index) external onlyOwners {
require(
removeOwnerSigners[msg.sender][_index] == false,
"You already signed this transaction"
);
RemoveOwner storage rmvOwner = removeOwner[_index];
require(!rmvOwner.approved, "Transaction already approved");
address toRemove = rmvOwner.remove;
rmvOwner.signatures += 1;
removeOwnerSigners[msg.sender][_index] = true;
if (rmvOwner.signatures >= threshold) {
uint256 index;
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] == toRemove) {
index = i;
isOwner[owners[i]] = false;
}
}
delete owners[index];
emit OwnerRemoved(toRemove, msg.sender);
rmvOwner.approved = true;
}
}
/**
* @notice Request to add an owner and adds a signature.
* @param _newOwner new owner to add.
*/
function addOwnerRequest(address _newOwner) external onlyOwners {
require(!isOwner[_newOwner], "address already an owner");
require(
_newOwner != address(this) && _newOwner != address(0),
"Incorrect address"
);
addOwner.push(
AddOwner({
add: _newOwner,
index: addOwnerIndex,
signatures: 0,
approved: false
})
);
addOwnerIndex += 1;
}
/**
* @notice adds an owner after reaching the threshold.
* @param _index the transaction index.
*/
function addOwnerApproval(uint256 _index) external onlyOwners {
require(
addOwnerSigners[msg.sender][_index] == false,
"You already signed this transaction"
);
AddOwner storage _addOwner = addOwner[_index];
address toAdd = _addOwner.add;
require(!_addOwner.approved, "Transaction already approved");
_addOwner.signatures += 1;
addOwnerSigners[msg.sender][_index] = true;
if (_addOwner.signatures >= threshold) {
owners.push(toAdd);
isOwner[toAdd] = true;
emit OwnerAdded(toAdd, msg.sender);
_addOwner.approved = true;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
/// ------------> VIEW HELPER FUNCTIONS. <--------------
/**
* @return returns an array of the indexes of the pending transactions.
*/
function pendingTransactionsIndex()
private
view
returns (uint256[] memory)
{
uint256 counter;
for (uint256 i = 0; i < transactions.length; i++) {
if (transactions[i].approved == false) {
counter += 1;
}
}
uint256[] memory result = new uint256[](counter);
uint256 index;
for (uint256 i = 0; i < transactions.length; i++) {
if (transactions[i].approved == false) {
result[index] = i;
index += 1;
}
}
return result;
}
/**
* @return an array of pending transactions in struct format.
*/
function pendingTransactionsData()
external
view
onlyOwners
returns (Transaction[] memory)
{
uint256[] memory pendingTr = pendingTransactionsIndex();
Transaction[] memory t = new Transaction[](pendingTr.length);
for (uint256 i = 0; i < pendingTr.length; i++) {
t[i] = transactions[pendingTr[i]];
}
return t;
}
/**
* @return an array of the indexes of the pending update threshold transactions.
*/
function pendingUpdatethresholdIndex()
private
view
returns (uint256[] memory)
{
uint256 counter;
for (uint256 i = 0; i < updatethreshold.length; i++) {
if (updatethreshold[i].approved == false) {
counter += 1;
}
}
uint256[] memory result = new uint256[](counter);
uint256 index;
for (uint256 i = 0; i < updatethreshold.length; i++) {
if (updatethreshold[i].approved == false) {
result[index] = i;
index += 1;
}
}
return result;
}
/**
* @return an array of the indexes of the pending update threshold transactions.
*/
function pendingUpdatethresholdData()
external
view
onlyOwners
returns (UpdateThreshold[] memory)
{
uint256[] memory pendingUQ = pendingUpdatethresholdIndex();
UpdateThreshold[] memory uq = new UpdateThreshold[](pendingUQ.length);
for (uint256 i = 0; i < pendingUQ.length; i++) {
uq[i] = updatethreshold[pendingUQ[i]];
}
return uq;
}
/**
* @return an array of the indexes of the pending remove owner transactions.
*/
function pendingRemoveOwnerIndex() private view returns (uint256[] memory) {
uint256 counter;
for (uint256 i = 0; i < removeOwner.length; i++) {
if (removeOwner[i].approved == false) {
counter += 1;
}
}
uint256[] memory result = new uint256[](counter);
uint256 index;
for (uint256 i = 0; i < removeOwner.length; i++) {
if (removeOwner[i].approved == false) {
result[index] = i;
index += 1;
}
}
return result;
}
///@return an array of pending remove owner transactions in struct format.
function pendingRemoveOwnerData()
external
view
onlyOwners
returns (RemoveOwner[] memory)
{
uint256[] memory pendingRO = pendingRemoveOwnerIndex();
RemoveOwner[] memory ro = new RemoveOwner[](pendingRO.length);
for (uint256 i = 0; i < pendingRO.length; i++) {
ro[i] = removeOwner[pendingRO[i]];
}
return ro;
}
///@return returns an array of the indexes of the pending add owner transactions.
function pendingAddOwnerIndex() private view returns (uint256[] memory) {
uint256 counter;
for (uint256 i = 0; i < addOwner.length; i++) {
if (addOwner[i].approved == false) {
counter += 1;
}
}
uint256[] memory result = new uint256[](counter);
uint256 index;
for (uint256 i = 0; i < addOwner.length; i++) {
if (addOwner[i].approved == false) {
result[index] = i;
index += 1;
}
}
return result;
}
///@return an array of pending add owner transactions in struct format.
function pendingAddOwnerData()
external
view
onlyOwners
returns (AddOwner[] memory)
{
uint256[] memory pendingAO = pendingAddOwnerIndex();
AddOwner[] memory ao = new AddOwner[](pendingAO.length);
for (uint256 i = 0; i < pendingAO.length; i++) {
ao[i] = addOwner[pendingAO[i]];
}
return ao;
}
///@return uint of total active owners.
function totalOwners() public view returns (uint256) {
uint256 result;
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] != address(0)) {
result += 1;
}
}
return result;
}
/// @return an array of the addresses of the owners.
function getOwnersAddress() external view returns (address[] memory) {
require(owners.length > 0, "0 owners not valid, ERROR!");
uint256 counter;
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] != address(0)) {
counter += 1;
}
}
address[] memory result = new address[](counter);
uint256 index;
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] != address(0)) {
result[index] = owners[i];
index += 1;
}
}
return result;
}
}
|
adds an owner after reaching the threshold. _index the transaction index./
|
function addOwnerApproval(uint256 _index) external onlyOwners {
require(
addOwnerSigners[msg.sender][_index] == false,
"You already signed this transaction"
);
AddOwner storage _addOwner = addOwner[_index];
address toAdd = _addOwner.add;
require(!_addOwner.approved, "Transaction already approved");
_addOwner.signatures += 1;
addOwnerSigners[msg.sender][_index] = true;
if (_addOwner.signatures >= threshold) {
owners.push(toAdd);
isOwner[toAdd] = true;
emit OwnerAdded(toAdd, msg.sender);
_addOwner.approved = true;
}
}
| 1,795,452 |
./full_match/1/0xa48c616144FD4429b216A86388CAb0Eed990cE87/sources/contracts/Strategy.sol
|
onlyStrategist or multisig:
|
function _cancelPendingTrades(uint256[] calldata _pendingTrades) internal {
for (uint256 i; i < _pendingTrades.length; i++) {
_cancelPendingTrade(_pendingTrades[i]);
}
}
| 8,293,414 |
./partial_match/1/0x67c5F13c56aEb40fd9a937214E5429dAf8A0CfC9/sources/contracts/FCNProduct.sol
|
Calculates the fees that should be collected from a given vault vaultAddress is the address of the vault/
|
function calculateFees(
address vaultAddress
) public view validVault(vaultAddress) returns (uint256 totalFee, uint256 managementFee, uint256 yieldFee) {
FCNVaultMetadata storage vaultMetadata = vaults[vaultAddress];
return vaultMetadata.calculateFees(managementFeeBps, yieldFeeBps);
}
| 15,753,074 |
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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;
}
}
contract ExternalInterface {
function giveItem(address _recipient, uint256 _traits) external;
function giveMultipleItems(address _recipient, uint256[] _traits) external;
function giveMultipleItemsToMultipleRecipients(address[] _recipients, uint256[] _traits) external;
function giveMultipleItemsAndDestroyMultipleItems(address _recipient, uint256[] _traits, uint256[] _tokenIds) external;
function destroyItem(uint256 _tokenId) external;
function destroyMultipleItems(uint256[] _tokenIds) external;
function updateItemTraits(uint256 _tokenId, uint256 _traits) external;
}
contract LootboxInterface {
event LootboxPurchased(address indexed owner, address indexed storeAddress, uint16 displayValue);
function buy(address _buyer) external;
}
/// @title ERC-165 Standard Interface Detection
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
/**
* @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);
function tokensOf(address _owner) public view returns (uint256[]);
}
/**
* @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 {
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken, ERC165 {
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the list of tokens owned by a requested address
* @param _owner address to query the tokens of
* @return uint256[] representing the list of tokens owned by the requested address
*/
function tokensOf(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Query if a contract implements an interface
* @param _interfaceID interfaceID being checked
* @return bool if the current contract supports the queried interface
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return _interfaceID == 0x01ffc9a7 || // ERC165
_interfaceID == 0x80ac58cd || // ERC721
_interfaceID == 0x780e9d63; // ERC721Enumerable
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
contract Base is ERC721Token, Ownable {
event NewCRLToken(address indexed owner, uint256 indexed tokenId, uint256 traits);
event UpdatedCRLToken(uint256 indexed UUID, uint256 indexed tokenId, uint256 traits);
uint256 TOKEN_UUID;
uint256 UPGRADE_UUID;
function _createToken(address _owner, uint256 _traits) internal {
// emit the creaton event
emit NewCRLToken(
_owner,
TOKEN_UUID,
_traits
);
// This will assign ownership, and also emit the Transfer event
_mint(_owner, TOKEN_UUID);
TOKEN_UUID++;
}
function _updateToken(uint256 _tokenId, uint256 _traits) internal {
// emit the upgrade event
emit UpdatedCRLToken(
UPGRADE_UUID,
_tokenId,
_traits
);
UPGRADE_UUID++;
}
// Eth balance controls
// We can withdraw eth balance of contract.
function withdrawBalance() onlyOwner external {
require(address(this).balance > 0);
msg.sender.transfer(address(this).balance);
}
}
contract LootboxStore is Base {
// mapping between specific Lootbox contract address to price in wei
mapping(address => uint256) ethPricedLootboxes;
// mapping between specific Lootbox contract address to price in NOS tokens
mapping(uint256 => uint256) NOSPackages;
uint256 UUID;
event NOSPurchased(uint256 indexed UUID, address indexed owner, uint256 indexed NOSAmtPurchased);
function addLootbox(address _lootboxAddress, uint256 _price) external onlyOwner {
ethPricedLootboxes[_lootboxAddress] = _price;
}
function removeLootbox(address _lootboxAddress) external onlyOwner {
delete ethPricedLootboxes[_lootboxAddress];
}
function buyEthLootbox(address _lootboxAddress) payable external {
// Verify the given lootbox contract exists and they've paid enough
require(ethPricedLootboxes[_lootboxAddress] != 0);
require(msg.value >= ethPricedLootboxes[_lootboxAddress]);
LootboxInterface(_lootboxAddress).buy(msg.sender);
}
function addNOSPackage(uint256 _NOSAmt, uint256 _ethPrice) external onlyOwner {
NOSPackages[_NOSAmt] = _ethPrice;
}
function removeNOSPackage(uint256 _NOSAmt) external onlyOwner {
delete NOSPackages[_NOSAmt];
}
function buyNOS(uint256 _NOSAmt) payable external {
require(NOSPackages[_NOSAmt] != 0);
require(msg.value >= NOSPackages[_NOSAmt]);
emit NOSPurchased(UUID, msg.sender, _NOSAmt);
UUID++;
}
}
contract Core is LootboxStore, ExternalInterface {
mapping(address => uint256) authorizedExternal;
function addAuthorizedExternal(address _address) external onlyOwner {
authorizedExternal[_address] = 1;
}
function removeAuthorizedExternal(address _address) external onlyOwner {
delete authorizedExternal[_address];
}
// Verify the caller of this function is a Lootbox contract or race, or crafting, or upgrade
modifier onlyAuthorized() {
require(ethPricedLootboxes[msg.sender] != 0 ||
authorizedExternal[msg.sender] != 0);
_;
}
function giveItem(address _recipient, uint256 _traits) onlyAuthorized external {
_createToken(_recipient, _traits);
}
function giveMultipleItems(address _recipient, uint256[] _traits) onlyAuthorized external {
for (uint i = 0; i < _traits.length; ++i) {
_createToken(_recipient, _traits[i]);
}
}
function giveMultipleItemsToMultipleRecipients(address[] _recipients, uint256[] _traits) onlyAuthorized external {
require(_recipients.length == _traits.length);
for (uint i = 0; i < _traits.length; ++i) {
_createToken(_recipients[i], _traits[i]);
}
}
function giveMultipleItemsAndDestroyMultipleItems(address _recipient, uint256[] _traits, uint256[] _tokenIds) onlyAuthorized external {
for (uint i = 0; i < _traits.length; ++i) {
_createToken(_recipient, _traits[i]);
}
for (i = 0; i < _tokenIds.length; ++i) {
_burn(ownerOf(_tokenIds[i]), _tokenIds[i]);
}
}
function destroyItem(uint256 _tokenId) onlyAuthorized external {
_burn(ownerOf(_tokenId), _tokenId);
}
function destroyMultipleItems(uint256[] _tokenIds) onlyAuthorized external {
for (uint i = 0; i < _tokenIds.length; ++i) {
_burn(ownerOf(_tokenIds[i]), _tokenIds[i]);
}
}
function updateItemTraits(uint256 _tokenId, uint256 _traits) onlyAuthorized external {
_updateToken(_tokenId, _traits);
}
}
|
Query if a contract implements an interface _interfaceID interfaceID being checked return bool if the current contract supports the queried interface/
|
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
}
| 11,939,706 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function base_virtual_price() external view returns (uint256);
function add_liquidity(
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// stETH pool
uint256[2] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool use_underlying
) external;
function add_liquidity(
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool use_underlying
) external;
function add_liquidity(
// stETH pool
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool use_underlying
) external payable;
function coins(int128) external view returns (address);
function pool() external view returns (address);
function base_coins(uint256) external view returns (address);
function underlying_coins(int128) external view returns (address);
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external;
function calc_withdraw_one_coin(uint256 _amount, int128 i) external view returns (uint256);
function calc_withdraw_one_coin(uint256 _amount, int128 i, bool use_underlying) external view returns (uint256);
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount,
bool use_underlying
) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external payable;
function balances(int128) external view returns (uint256);
function get_dy(
int128 from,
int128 to,
uint256 _from_amount
) external view returns (uint256);
function calc_token_amount( uint256[2] calldata amounts, bool is_deposit) external view returns (uint256);
function calc_token_amount( uint256[3] calldata amounts, bool is_deposit) external view returns (uint256);
function calc_token_amount( uint256[4] calldata amounts, bool is_deposit) external view returns (uint256);
}
// Part: IERC20Extended
interface IERC20Extended{
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
// Part: IUni
interface IUni {
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: Zap
interface Zap {
function remove_liquidity_one_coin(
uint256,
int128,
uint256
) external;
function remove_liquidity_one_coin(
uint256,
int128,
uint256,
bool
) external;
}
// Part: iearn-finance/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: ICrvV3
interface ICrvV3 is IERC20 {
function minter() external view returns (address);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.2";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
// Import interfaces for many popular DeFi projects, or add your own!
//import "../interfaces/<protocol>/<Interface>.sol";
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
ICurveFi public curvePool;// = ICurveFi(address(0x4CA9b3063Ec5866A4B82E437059D2C43d1be596F));
Zap public zapOut;
ICurveFi public basePool;
ICrvV3 public curveToken;// = ICrvV3(address(0xb19059ebb43466C323583928285a49f558E572Fd));
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
VaultAPI public yvToken;// = IVaultV1(address(0x46AFc2dfBd1ea0c0760CAD8262A5838e803A37e5));
//IERC20Extended public middleToken; // the token between bluechip and curve pool
uint256 public lastInvest;
uint256 public minTimePerInvest;// = 3600;
uint256 public maxSingleInvest;// // 2 hbtc per hour default
uint256 public slippageProtectionIn;// = 50; //out of 10000. 50 = 0.5%
uint256 public slippageProtectionOut;// = 50; //out of 10000. 50 = 0.5%
uint256 public constant DENOMINATOR = 10_000;
uint8 private want_decimals;
uint8 private middle_decimals;
int128 public curveId;
uint256 public poolSize;
bool public hasUnderlying;
address public metaToken;
bool public withdrawProtection;
constructor(
address _vault,
uint256 _maxSingleInvest,
uint256 _minTimePerInvest,
uint256 _slippageProtectionIn,
address _curvePool,
address _zapOut,
address _curveToken,
address _yvToken,
uint256 _poolSize,
address _metaToken,
bool _hasUnderlying
) public BaseStrategy(_vault) {
_initializeStrat(_maxSingleInvest, _minTimePerInvest, _slippageProtectionIn, _curvePool, _zapOut, _curveToken, _yvToken, _poolSize, _metaToken, _hasUnderlying);
}
function initialize(
address _vault,
address _strategist,
uint256 _maxSingleInvest,
uint256 _minTimePerInvest,
uint256 _slippageProtectionIn,
address _curvePool,
address _zapOut,
address _curveToken,
address _yvToken,
uint256 _poolSize,
address _metaToken,
bool _hasUnderlying
) external {
//note: initialise can only be called once. in _initialize in BaseStrategy we have: require(address(want) == address(0), "Strategy already initialized");
_initialize(_vault, _strategist, _strategist, _strategist);
_initializeStrat(_maxSingleInvest, _minTimePerInvest, _slippageProtectionIn, _curvePool, _zapOut, _curveToken, _yvToken, _poolSize, _metaToken, _hasUnderlying);
}
function _initializeStrat(
uint256 _maxSingleInvest,
uint256 _minTimePerInvest,
uint256 _slippageProtectionIn,
address _curvePool,
address _zapOut,
address _curveToken,
address _yvToken,
uint256 _poolSize,
address _metaToken,
bool _hasUnderlying
) internal {
require(want_decimals == 0, "Already Initialized");
require(_poolSize > 1 && _poolSize < 5, "incorrect pool size");
curvePool = ICurveFi(_curvePool);
zapOut = Zap(_zapOut);
if(_metaToken != address(0)) {
basePool = ICurveFi(curvePool.pool());
metaToken = _metaToken;
for(uint i = 0; i < _poolSize; i++){
if( i == 0){
if(curvePool.coins(0) == address(want)){
require(false, "ONLY USE META FOR BASE");
}
}else{
if(curvePool.base_coins(i-1) == address(want)){
curveId = int128(i);
break;
}
}
if(i == _poolSize - 1){ // doesnt matter if it overflows
require(false, "incorrect want for curve pool");
}
}
} else {
basePool = ICurveFi(_curvePool);
if(curvePool.coins(0) == address(want) || (_hasUnderlying && curvePool.underlying_coins(0) == address(want) )){
curveId = 0;
}else if ( curvePool.coins(1) == address(want) || (_hasUnderlying && curvePool.underlying_coins(1) == address(want) )){
curveId = 1;
}else if ( curvePool.coins(2) == address(want) || (_hasUnderlying && curvePool.underlying_coins(2) == address(want) )){
curveId = 2;
}else if ( curvePool.coins(3) == address(want) || (_hasUnderlying && curvePool.underlying_coins(3) == address(want) )){
//will revert if there are not enough coins
curveId = 3;
}else{
require(false, "incorrect want for curve pool");
}
}
maxSingleInvest = _maxSingleInvest;
minTimePerInvest = _minTimePerInvest;
slippageProtectionIn = _slippageProtectionIn;
slippageProtectionOut = _slippageProtectionIn; // use In to start with to save on stack
poolSize = _poolSize;
hasUnderlying = _hasUnderlying;
yvToken = VaultAPI(_yvToken);
curveToken = ICrvV3(_curveToken);
_setupStatics();
}
function _setupStatics() internal {
maxReportDelay = 86400;
profitFactor = 1500;
minReportDelay = 3600;
debtThreshold = 100*1e18;
withdrawProtection = true;
want_decimals = IERC20Extended(address(want)).decimals();
want.safeApprove(address(curvePool), uint256(-1));
curveToken.approve(address(zapOut), uint256(-1));
//deposit contract needs permissions
if(metaToken != address(0)){
IERC20(metaToken).safeApprove(address(curvePool), uint256(-1)); // 3crv
curveToken.approve(address(curvePool), uint256(-1));
}
curveToken.approve(address(yvToken), uint256(-1));
}
event Cloned(address indexed clone);
function cloneSingleSidedCurve(
address _vault,
address _strategist,
uint256 _maxSingleInvest,
uint256 _minTimePerInvest,
uint256 _slippageProtectionIn,
address _curvePool,
address _zapOut,
address _curveToken,
address _yvToken,
uint256 _poolSize,
address _metaToken,
bool _hasUnderlying
) external returns (address newStrategy){
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _maxSingleInvest, _minTimePerInvest, _slippageProtectionIn, _curvePool, _zapOut, _curveToken, _yvToken, _poolSize, _metaToken, _hasUnderlying);
emit Cloned(newStrategy);
}
function name() external override view returns (string memory) {
return string(abi.encodePacked("SingleSidedCrv", IERC20Extended(address(want)).symbol()));
}
function updateMinTimePerInvest(uint256 _minTimePerInvest) public onlyAuthorized {
minTimePerInvest = _minTimePerInvest;
}
function updateMaxSingleInvest(uint256 _maxSingleInvest) public onlyAuthorized {
maxSingleInvest = _maxSingleInvest;
}
function updateSlippageProtectionIn(uint256 _slippageProtectionIn) public onlyAuthorized {
slippageProtectionIn = _slippageProtectionIn;
}
function updateSlippageProtectionOut(uint256 _slippageProtectionOut) public onlyAuthorized {
slippageProtectionOut = _slippageProtectionOut;
}
function delegatedAssets() public override view returns (uint256) {
return vault.strategies(address(this)).totalDebt;
}
function estimatedTotalAssets() public override view returns (uint256) {
uint256 totalCurveTokens = curveTokensInYVault().add(curveToken.balanceOf(address(this)));
return want.balanceOf(address(this)).add(curveTokenToWant(totalCurveTokens));
}
// returns value of total
function curveTokenToWant(uint256 tokens) public view returns (uint256) {
if(tokens == 0){
return 0;
}
uint256 virtualOut = virtualPriceToWant().mul(tokens).div(1e18);
return virtualOut;
}
//we lose some precision here. but it shouldnt matter as we are underestimating
function virtualPriceToWant() public view returns (uint256) {
uint256 virtualPrice = basePool.get_virtual_price();
/*if(metaToken){
//warning: base virtual price is not cached and not live
virtualPrice = virtualPrice.mul(basePool.base_virtual_price()).div(1e18);
}*/
if(want_decimals < 18){
return virtualPrice.div(10 ** (uint256(uint8(18) - want_decimals)));
}else{
return virtualPrice;
}
}
/*function virtualPriceToMiddle() public view returns (uint256) {
if(middle_decimals < 18){
return curvePool.get_virtual_price().div(10 ** (uint256(uint8(18) - middle_decimals)));
}else{
return curvePool.get_virtual_price();
}
}*/
function curveTokensInYVault() public view returns (uint256) {
uint256 balance = yvToken.balanceOf(address(this));
if(yvToken.totalSupply() == 0){
//needed because of revert on priceperfullshare if 0
return 0;
}
uint256 pricePerShare = yvToken.pricePerShare();
//curve tokens are 1e18 decimals
return balance.mul(pricePerShare).div(1e18);
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_debtPayment = _debtOutstanding;
uint256 debt = vault.strategies(address(this)).totalDebt;
uint256 currentValue = estimatedTotalAssets();
uint256 wantBalance = want.balanceOf(address(this));
if(debt < currentValue){
//profit
_profit = currentValue.sub(debt);
}else{
_loss = debt.sub(currentValue);
}
uint256 toFree = _debtPayment.add(_profit);
if(toFree > wantBalance){
toFree = toFree.sub(wantBalance);
(, uint256 withdrawalLoss) = withdrawSome(toFree);
//when we withdraw we can lose money in the withdrawal
if(withdrawalLoss < _profit){
_profit = _profit.sub(withdrawalLoss);
}else{
_loss = _loss.add(withdrawalLoss.sub(_profit));
_profit = 0;
}
wantBalance = want.balanceOf(address(this));
if(wantBalance < _profit){
_profit = wantBalance;
_debtPayment = 0;
}else if (wantBalance < _debtPayment.add(_profit)){
_debtPayment = wantBalance.sub(_profit);
}
}
/*if(doHealthCheck && debt > 0){
//set to 10_000 to let any profit through
if(profitLimitRatio < DENOMINATOR){
require(_profit < debt.mul(profitLimitRatio).div(DENOMINATOR), "PROFIT TOO HIGH");
}
require(_loss < debt.mul(lossLimitRatio).div(DENOMINATOR), "LOSS TOO HIGH");
}*/
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
(_amountFreed, ) = liquidatePosition(1e36); //we can request a lot. dont use max because of overflow
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function tendTrigger(uint256 callCost) public override view returns (bool) {
uint256 wantBal = want.balanceOf(address(this));
uint256 _wantToInvest = Math.min(wantBal, maxSingleInvest);
if(lastInvest.add(minTimePerInvest) < block.timestamp && _wantToInvest > 1 && _checkSlip(_wantToInvest)){
//return true;
}
}
function _checkSlip(uint256 _wantToInvest) public view returns (bool){
return true;
}
function adjustPosition(uint256 _debtOutstanding) internal override {
if(lastInvest.add(minTimePerInvest) > block.timestamp ){
return;
}
// Invest the rest of the want
uint256 _wantToInvest = Math.min(want.balanceOf(address(this)), maxSingleInvest);
if (_wantToInvest > 0) {
//add to curve (single sided)
if(_checkSlip(_wantToInvest)){
uint256 expectedOut = _wantToInvest.mul(1e18).div(virtualPriceToWant());
uint256 maxSlip = expectedOut.mul(DENOMINATOR.sub(slippageProtectionIn)).div(DENOMINATOR);
//pool size cannot be more than 4 or less than 2
if(poolSize == 2){
uint256[2] memory amounts;
amounts[uint256(curveId)] = _wantToInvest;
if(hasUnderlying){
curvePool.add_liquidity(amounts, maxSlip, true);
}else{
curvePool.add_liquidity(amounts, maxSlip);
}
}else if (poolSize == 3){
uint256[3] memory amounts;
amounts[uint256(curveId)] = _wantToInvest;
if(hasUnderlying){
curvePool.add_liquidity(amounts, maxSlip, true);
}else{
curvePool.add_liquidity(amounts, maxSlip);
}
}else{
uint256[4] memory amounts;
amounts[uint256(curveId)] = _wantToInvest;
if(hasUnderlying){
curvePool.add_liquidity(amounts, maxSlip, true);
}else{
curvePool.add_liquidity(amounts, maxSlip);
}
}
//now add to yearn
yvToken.deposit();
lastInvest = block.timestamp;
}else{
require(false, "quee");
}
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 wantBal = want.balanceOf(address(this));
if(wantBal < _amountNeeded){
(_liquidatedAmount, _loss) = withdrawSome(_amountNeeded.sub(wantBal));
}
_liquidatedAmount = Math.min(_amountNeeded, _liquidatedAmount.add(wantBal));
}
//safe to enter more than we have
function withdrawSome(uint256 _amount) internal returns (uint256 _liquidatedAmount, uint256 _loss) {
uint256 wantBalanceBefore = want.balanceOf(address(this));
//let's take the amount we need if virtual price is real. Let's add the
uint256 virtualPrice = virtualPriceToWant();
uint256 amountWeNeedFromVirtualPrice = _amount.mul(1e18).div(virtualPrice);
uint256 crvBeforeBalance = curveToken.balanceOf(address(this)); //should be zero but just incase...
uint256 pricePerFullShare = yvToken.pricePerShare();
uint256 amountFromVault = amountWeNeedFromVirtualPrice.mul(1e18).div(pricePerFullShare);
uint256 yBalance = yvToken.balanceOf(address(this));
if(amountFromVault > yBalance){
amountFromVault = yBalance;
//this is not loss. so we amend amount
uint256 _amountOfCrv = amountFromVault.mul(pricePerFullShare).div(1e18);
_amount = _amountOfCrv.mul(virtualPrice).div(1e18);
}
yvToken.withdraw(amountFromVault);
if(withdrawProtection){
//this tests that we liquidated all of the expected ytokens. Without it if we get back less then will mark it is loss
require(yBalance.sub(yvToken.balanceOf(address(this))) >= amountFromVault.sub(1), "YVAULTWITHDRAWFAILED");
}
uint256 toWithdraw = curveToken.balanceOf(address(this)).sub(crvBeforeBalance);
//if we have less than 18 decimals we need to lower the amount out
uint256 maxSlippage = toWithdraw.mul(DENOMINATOR.sub(slippageProtectionOut)).div(DENOMINATOR);
if(want_decimals < 18){
maxSlippage = maxSlippage.div(10 ** (uint256(uint8(18) - want_decimals)));
}
if(hasUnderlying){
zapOut.remove_liquidity_one_coin(toWithdraw, curveId, maxSlippage, true);
}else{
zapOut.remove_liquidity_one_coin(toWithdraw, curveId, maxSlippage);
}
uint256 diff = want.balanceOf(address(this)).sub(wantBalanceBefore);
if(diff > _amount){
_liquidatedAmount = _amount;
}else{
_liquidatedAmount = diff;
_loss = _amount.sub(diff);
}
}
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
function prepareMigration(address _newStrategy) internal override {
yvToken.transfer(_newStrategy, yvToken.balanceOf(address(this)));
}
// Override this to add all tokens/tokenized positions this contract manages
// on a *persistent* basis (e.g. not just for swapping back to want ephemerally)
// NOTE: Do *not* include `want`, already included in `sweep` below
//
// Example:
//
// function protectedTokens() internal override view returns (address[] memory) {
// address[] memory protected = new address[](3);
// protected[0] = tokenA;
// protected[1] = tokenB;
// protected[2] = tokenC;
// return protected;
// }
function protectedTokens()
internal
override
view
returns (address[] memory)
{
address[] memory protected = new address[](1);
protected[0] = address(yvToken);
return protected;
}
}
|
safe to enter more than we havelet's take the amount we need if virtual price is real. Let's add the
|
function withdrawSome(uint256 _amount) internal returns (uint256 _liquidatedAmount, uint256 _loss) {
uint256 wantBalanceBefore = want.balanceOf(address(this));
uint256 virtualPrice = virtualPriceToWant();
uint256 amountWeNeedFromVirtualPrice = _amount.mul(1e18).div(virtualPrice);
uint256 pricePerFullShare = yvToken.pricePerShare();
uint256 amountFromVault = amountWeNeedFromVirtualPrice.mul(1e18).div(pricePerFullShare);
uint256 yBalance = yvToken.balanceOf(address(this));
if(amountFromVault > yBalance){
amountFromVault = yBalance;
uint256 _amountOfCrv = amountFromVault.mul(pricePerFullShare).div(1e18);
_amount = _amountOfCrv.mul(virtualPrice).div(1e18);
}
yvToken.withdraw(amountFromVault);
if(withdrawProtection){
require(yBalance.sub(yvToken.balanceOf(address(this))) >= amountFromVault.sub(1), "YVAULTWITHDRAWFAILED");
}
uint256 toWithdraw = curveToken.balanceOf(address(this)).sub(crvBeforeBalance);
uint256 maxSlippage = toWithdraw.mul(DENOMINATOR.sub(slippageProtectionOut)).div(DENOMINATOR);
if(want_decimals < 18){
maxSlippage = maxSlippage.div(10 ** (uint256(uint8(18) - want_decimals)));
}
if(hasUnderlying){
zapOut.remove_liquidity_one_coin(toWithdraw, curveId, maxSlippage, true);
zapOut.remove_liquidity_one_coin(toWithdraw, curveId, maxSlippage);
}
uint256 diff = want.balanceOf(address(this)).sub(wantBalanceBefore);
}else{
if(diff > _amount){
_liquidatedAmount = _amount;
_liquidatedAmount = diff;
_loss = _amount.sub(diff);
}
}else{
}
| 13,946,398 |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
// Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below).
contract LiquidationWithdrawer {
function withdrawLiquidation(
address financialContractAddress,
uint256 liquidationId,
address sponsor
) public returns (FixedPoint.Unsigned memory) {
return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor);
}
}
interface IFinancialContract {
function withdrawLiquidation(uint256 liquidationId, address sponsor)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @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-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
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, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 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), "SignedSafeMath: subtraction overflow");
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), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
import "../GSN/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.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
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);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the
* upgrade process for Voting.sol.
* @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only
* the ones that need to be performed atomically.
*/
contract VotingUpgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
// Address to call setMigrated on the old voting contract.
address public setMigratedAddress;
/**
* @notice Removes an address from the whitelist.
* @param _governor the Governor contract address.
* @param _existingVoting the current/existing Voting contract address.
* @param _newVoting the new Voting deployment address.
* @param _finder the Finder contract address.
* @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to
* old voting contract (used to claim rewards on others' behalf). Note: this address
* can always be changed by the voters.
*/
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder,
address _setMigratedAddress
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
setMigratedAddress = _setMigratedAddress;
}
/**
* @notice Performs the atomic portion of the upgrade process.
* @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and
* returns ownership of the existing Voting contract and Finder back to the Governor.
*/
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set the preset "migrated" address to allow this address to claim rewards on voters' behalf.
// This also effectively shuts down the existing voting contract so new votes cannot be triggered.
existingVoting.setMigrated(setMigratedAddress);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData);
event PushedPrice(
address indexed pusher,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price
);
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData);
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
emit PushedPrice(msg.sender, identifier, time, ancillaryData, price);
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice,
uint256 expirationTimestamp,
address currency
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice,
request.expirationTime,
address(request.currency)
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
// Avoids stack too deep compilation error.
{
// Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it
// proportionally more expensive to delay the resolution even if the proposer and disputer are the same
// party.
uint256 burnedBond = _computeBurnedBond(request);
// The total fee is the burned bond and the final fee added together.
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
// Unburned portion of the loser's bond = 1 - burned bond.
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
// Winner gets:
// - Their bond back.
// - The unburned portion of the loser's bond.
// - Their final fee back.
// - The request reward (if not already refunded -- if refunded, it will be set to 0).
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request) private view returns (uint256) {
// burnedBond = floor(bond / 2)
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
// Implement collateralCurrency so that this contract simulates a financial contract whose collateral
// token can be fetched by off-chain clients.
IERC20 public collateralCurrency;
// Manually set an expiration timestamp to simulate expiry price requests
uint256 public expirationTimestamp;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
// Set collateral currency to last requested currency:
collateralCurrency = currency;
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function settleAndGetPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function setExpirationTimestamp(uint256 _expirationTimestamp) external {
expirationTimestamp = _expirationTimestamp;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) {
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract.
(
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
) = getOutstandingRegularFees(time);
lastPaymentTime = time;
// If there are no fees to pay then exit early.
if (totalPaid.isEqual(0)) {
return totalPaid;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more
* than the total collateral within the contract then the totalPaid returned is full contract collateral amount.
* @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
* @return regularFee outstanding unpaid regular fee.
* @return latePenalty outstanding unpaid late fee for being late in previous fee payments.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
*/
function getOutstandingRegularFees(uint256 time)
public
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
)
{
StoreInterface store = _getStore();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral or if fees were already paid during this block.
if (collateralPool.isEqual(0) || lastPaymentTime == time) {
return (regularFee, latePenalty, totalPaid);
}
(regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool);
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return (regularFee, latePenalty, totalPaid);
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Returns the user's collateral minus any pending fees that have yet to be subtracted.
function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory)
{
(, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) =
getOutstandingRegularFees(getCurrentTime());
if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral;
// Calculate the total outstanding regular fee as a fraction of the total contract PFC.
FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc());
// Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee.
return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee));
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
*/
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
)
);
int256 optimisticOraclePrice =
optimisticOracle.settleAndGetPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
);
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05`
* (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value
* {ERC20} uses, unless {_setupDecimals} is called.
*
* NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic
* of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view returns (uint8);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Inspired by:
* - https://github.com/pie-dao/vested-token-migration-app
* - https://github.com/Uniswap/merkle-distributor
* - https://github.com/balancer-labs/erc20-redeemable
*
* @title MerkleDistributor contract.
* @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify
* multiple Merkle roots distributions with customized reward currencies.
* @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly.
*/
contract MerkleDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// A Window maps a Merkle root to a reward token address.
struct Window {
// Merkle root describing the distribution.
bytes32 merkleRoot;
// Currency in which reward is processed.
IERC20 rewardToken;
// IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical
// data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code>
// <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier
// for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply
// go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>.
string ipfsHash;
}
// Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`.
struct Claim {
uint256 windowIndex;
uint256 amount;
uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim.
address account;
bytes32[] merkleProof;
}
// Windows are mapped to arbitrary indices.
mapping(uint256 => Window) public merkleWindows;
// Index of next created Merkle root.
uint256 public nextCreatedIndex;
// Track which accounts have claimed for each window index.
// Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
/****************************************
* EVENTS
****************************************/
event Claimed(
address indexed caller,
uint256 windowIndex,
address indexed account,
uint256 accountIndex,
uint256 amount,
address indexed rewardToken
);
event CreatedWindow(
uint256 indexed windowIndex,
uint256 rewardsDeposited,
address indexed rewardToken,
address owner
);
event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency);
event DeleteWindow(uint256 indexed windowIndex, address owner);
/****************************
* ADMIN FUNCTIONS
****************************/
/**
* @notice Set merkle root for the next available window index and seed allocations.
* @notice Callable only by owner of this contract. Caller must have approved this contract to transfer
* `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the
* owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all
* claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur
* because we do not segregate reward balances by window, for code simplicity purposes.
* (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must
* subsequently transfer in rewards or the following situation can occur).
* Example race situation:
* - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and
* claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101.
* - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner
* correctly set `rewardsToDeposit` this time.
* - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence:
* (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens.
* (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens.
* (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens.
* - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would
* succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
* @param rewardsToDeposit amount of rewards to deposit to seed this allocation.
* @param rewardToken ERC20 reward token.
* @param merkleRoot merkle root describing allocation.
* @param ipfsHash hash of IPFS object, conveniently stored for clients
*/
function setWindow(
uint256 rewardsToDeposit,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) external onlyOwner {
uint256 indexToSet = nextCreatedIndex;
nextCreatedIndex = indexToSet.add(1);
_setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash);
}
/**
* @notice Delete merkle root at window index.
* @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state.
* @param windowIndex merkle root index to delete.
*/
function deleteWindow(uint256 windowIndex) external onlyOwner {
delete merkleWindows[windowIndex];
emit DeleteWindow(windowIndex, msg.sender);
}
/**
* @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly.
* @dev Callable only by owner.
* @param rewardCurrency rewards to withdraw from contract.
* @param amount amount of rewards to withdraw.
*/
function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner {
IERC20(rewardCurrency).safeTransfer(msg.sender, amount);
emit WithdrawRewards(msg.sender, amount, rewardCurrency);
}
/****************************
* NON-ADMIN FUNCTIONS
****************************/
/**
* @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail
* if any individual claims within the batch would fail.
* @dev Optimistically tries to batch together consecutive claims for the same account and same
* reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method
* is to pass in an array of claims sorted by account and reward currency.
* @param claims array of claims to claim.
*/
function claimMulti(Claim[] memory claims) external {
uint256 batchedAmount = 0;
uint256 claimCount = claims.length;
for (uint256 i = 0; i < claimCount; i++) {
Claim memory _claim = claims[i];
_verifyAndMarkClaimed(_claim);
batchedAmount = batchedAmount.add(_claim.amount);
// If the next claim is NOT the same account or the same token (or this claim is the last one),
// then disburse the `batchedAmount` to the current claim's account for the current claim's reward token.
uint256 nextI = i + 1;
address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken);
if (
nextI == claimCount ||
// This claim is last claim.
claims[nextI].account != _claim.account ||
// Next claim account is different than current one.
address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken
// Next claim reward token is different than current one.
) {
IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount);
batchedAmount = 0;
}
}
}
/**
* @notice Claim amount of reward tokens for account, as described by Claim input object.
* @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the
* values stored in the merkle root for the `_claim`'s `windowIndex` this method
* will revert.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
*/
function claim(Claim memory _claim) public {
_verifyAndMarkClaimed(_claim);
merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount);
}
/**
* @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at
* `windowIndex`.
* @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`.
* The onus is on the Owner of this contract to submit only valid Merkle roots.
* @param windowIndex merkle root to check.
* @param accountIndex account index to check within window index.
* @return True if claim has been executed already, False otherwise.
*/
function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
/**
* @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given
* window index.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
* @return valid True if leaf exists.
*/
function verifyClaim(Claim memory _claim) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex));
return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf);
}
/****************************
* PRIVATE FUNCTIONS
****************************/
// Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
claimedBitMap[windowIndex][claimedWordIndex] =
claimedBitMap[windowIndex][claimedWordIndex] |
(1 << claimedBitIndex);
}
// Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root.
function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
}
// Verify claim is valid and mark it as completed in this contract.
function _verifyAndMarkClaimed(Claim memory _claim) private {
// Check claimed proof against merkle window at given index.
require(verifyClaim(_claim), "Incorrect merkle proof");
// Check the account has not yet claimed for this window.
require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window");
// Proof is correct and claim has not occurred yet, mark claimed complete.
_setClaimed(_claim.windowIndex, _claim.accountIndex);
emit Claimed(
msg.sender,
_claim.windowIndex,
_claim.account,
_claim.accountIndex,
_claim.amount,
address(merkleWindows[_claim.windowIndex].rewardToken)
);
}
}
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier paysRegularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public paysRegularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPercentage).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _updateFundingRate() internal {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
_updateFundingRate(); // Update the funding rate if there is a resolved proposal.
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
fundingRate.rate,
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPercentage;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPercentage.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPercentage.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final
* fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at
// liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: `payToLiquidator` should never be below zero since we enforce that
// (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Post-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier
* & if it is before expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is after contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return identifier;
} else {
return financialProductTransformedIdentifiers[msg.sender];
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title KPI Options Financial Product Library
* @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract.
* If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1.
* Post-expiry, the collateral requirement is left as 1 and the price is left unchanged.
*/
contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable {
/**
* @notice Returns a transformed price for pre-expiry price requests.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
// If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with
// each token backed 1:2 by collateral currency. Post-expiry, leave unchanged.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(2);
} else {
return oraclePrice;
}
}
/**
* @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled to a flat rate.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Always return 1.
return FixedPoint.fromUnscaledUint(1);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title CoveredCall Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If
* ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by
* (oraclePrice - strikePrice) / oraclePrice;
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH.
* If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200).
* If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400).
* If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH.
*/
contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => FixedPoint.Unsigned) private financialProductStrikes;
/**
* @notice Enables any address to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the covered call to be applied to the financial product.
* @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.
* e) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the call option payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThanOrEqual(strike)) {
return FixedPoint.fromUnscaledUint(0);
} else {
// Token expires to be worth the fraction of a collateral token that's in the money.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100).
// Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always
// true.
return (oraclePrice.sub(strike)).div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the covered call payout structure.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// Always return 1 because option must be collateralized by 1 token.
return FixedPoint.fromUnscaledUint(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/ExpandedERC20.sol";
contract TokenSender {
function transferERC20(
address tokenAddress,
address recipientAddress,
uint256 amount
) public returns (bool) {
IERC20 token = IERC20(tokenAddress);
token.transfer(recipientAddress, amount);
return true;
}
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IDepositExecute.sol";
import "./IBridge.sol";
import "./IERCHandler.sol";
import "./IGenericHandler.sol";
/**
@title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl {
using SafeMath for uint256;
uint8 public _chainID;
uint256 public _relayerThreshold;
uint256 public _totalRelayers;
uint256 public _totalProposals;
uint256 public _fee;
uint256 public _expiry;
enum Vote { No, Yes }
enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled }
struct Proposal {
bytes32 _resourceID;
bytes32 _dataHash;
address[] _yesVotes;
address[] _noVotes;
ProposalStatus _status;
uint256 _proposedBlock;
}
// destinationChainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// depositNonce => destinationChainID => bytes
mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords;
// destinationChainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals;
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
event RelayerThresholdChanged(uint256 indexed newThreshold);
event RelayerAdded(address indexed relayer);
event RelayerRemoved(address indexed relayer);
event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce);
event ProposalEvent(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID,
bytes32 dataHash
);
event ProposalVote(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender),
"sender is not relayer or admin"
);
}
function _onlyAdmin() private {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role");
}
function _onlyRelayers() private {
require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role");
}
/**
@notice Initializes Bridge, creates and grants {msg.sender} the admin role,
creates and grants {initialRelayers} the relayer role.
@param chainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor(
uint8 chainID,
address[] memory initialRelayers,
uint256 initialRelayerThreshold,
uint256 fee,
uint256 expiry
) public {
_chainID = chainID;
_relayerThreshold = initialRelayerThreshold;
_fee = fee;
_expiry = expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
_totalRelayers++;
}
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause();
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause();
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external onlyAdmin {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
_totalRelayers++;
}
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external onlyAdmin {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
_totalRelayers--;
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(
address handlerAddress,
bytes32 resourceID,
address tokenAddress
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Returns a proposal.
@param originChainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(
uint8 originChainID,
uint64 depositNonce,
bytes32 dataHash
) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee;
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
function adminWithdraw(
address handlerAddress,
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(tokenAddress, recipient, amountOrTokenID);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationChainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event.
*/
function deposit(
uint8 destinationChainID,
bytes32 resourceID,
bytes calldata data
) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationChainID];
_depositRecords[depositNonce][destinationChainID] = data;
IDepositExecute depositHandler = IDepositExecute(handler);
depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);
emit Deposit(destinationChainID, resourceID, depositNonce);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 resourceID,
bytes32 dataHash
) external onlyRelayers whenNotPaused {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled");
require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");
if (uint256(proposal._status) == 0) {
++_totalProposals;
_proposals[nonceAndID][dataHash] = Proposal({
_resourceID: resourceID,
_dataHash: dataHash,
_yesVotes: new address[](1),
_noVotes: new address[](0),
_status: ProposalStatus.Active,
_proposedBlock: block.number
});
proposal._yesVotes[0] = msg.sender;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
} else {
if (block.number.sub(proposal._proposedBlock) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash);
} else {
require(dataHash == proposal._dataHash, "datahash mismatch");
proposal._yesVotes.push(msg.sender);
}
}
if (proposal._status != ProposalStatus.Cancelled) {
_hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);
// If _depositThreshold is set to 1, then auto finalize
// or if _relayerThreshold has been exceeded
if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash);
}
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 dataHash
) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
*/
function executeProposal(
uint8 chainID,
uint64 depositNonce,
bytes calldata data,
bytes32 resourceID
) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
require(dataHash == proposal._dataHash, "data doesn't match datahash");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
depositHandler.executeProposal(proposal._resourceID, data);
emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity ^0.6.0;
/**
@title Interface for handler contracts that support deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IDepositExecute {
/**
@notice It is intended that deposit are made using the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for Bridge contract.
@author ChainSafe Systems.
*/
interface IBridge {
/**
@notice Exposing getter for {_chainID} instead of forcing the use of call.
@return uint8 The {_chainID} that is currently set for the Bridge contract.
*/
function _chainID() external returns (uint8);
}
pragma solidity ^0.6.0;
/**
@title Interface to be used with handlers that support ERC20s and ERC721s.
@author ChainSafe Systems.
*/
interface IERCHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release.
*/
function withdraw(
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for handler that handles generic deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IGenericHandler {
/**
@notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./IGenericHandler.sol";
/**
@title Handles generic deposits and deposit executions.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract GenericHandler is IGenericHandler {
address public _bridgeAddress;
struct DepositRecord {
uint8 _destinationChainID;
address _depositer;
bytes32 _resourceID;
bytes _metaData;
}
// depositNonce => Deposit Record
mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords;
// resourceID => contract address
mapping(bytes32 => address) public _resourceIDToContractAddress;
// contract address => resourceID
mapping(address => bytes32) public _contractAddressToResourceID;
// contract address => deposit function signature
mapping(address => bytes4) public _contractAddressToDepositFunctionSignature;
// contract address => execute proposal function signature
mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature;
// token contract address => is whitelisted
mapping(address => bool) public _contractWhitelist;
modifier onlyBridge() {
_onlyBridge();
_;
}
function _onlyBridge() private {
require(msg.sender == _bridgeAddress, "sender must be bridge contract");
}
/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param initialResourceIDs Resource IDs used to identify a specific contract address.
These are the Resource IDs this contract will initially support.
@param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be
called to perform deposit and execution calls.
@param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {deposit}
@param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {executeProposal}
@dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures},
and {initialExecuteFunctionSignatures} must all have the same length. Also,
values must be ordered in the way that that index x of any mentioned array
must be intended for value x of any other array, e.g. {initialContractAddresses}[0]
is the intended address for {initialDepositFunctionSignatures}[0].
*/
constructor(
address bridgeAddress,
bytes32[] memory initialResourceIDs,
address[] memory initialContractAddresses,
bytes4[] memory initialDepositFunctionSignatures,
bytes4[] memory initialExecuteFunctionSignatures
) public {
require(
initialResourceIDs.length == initialContractAddresses.length,
"initialResourceIDs and initialContractAddresses len mismatch"
);
require(
initialContractAddresses.length == initialDepositFunctionSignatures.length,
"provided contract addresses and function signatures len mismatch"
);
require(
initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length,
"provided deposit and execute function signatures len mismatch"
);
_bridgeAddress = bridgeAddress;
for (uint256 i = 0; i < initialResourceIDs.length; i++) {
_setResource(
initialResourceIDs[i],
initialContractAddresses[i],
initialDepositFunctionSignatures[i],
initialExecuteFunctionSignatures[i]
);
}
}
/**
@param depositNonce This ID will have been generated by the Bridge contract.
@param destId ID of chain deposit will be bridged to.
@return DepositRecord which consists of:
- _destinationChainID ChainID deposited tokens are intended to end up on.
- _resourceID ResourceID used when {deposit} was executed.
- _depositer Address that initially called {deposit} in the Bridge contract.
- _metaData Data to be passed to method executed in corresponding {resourceID} contract.
*/
function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) {
return _depositRecords[destId][depositNonce];
}
/**
@notice First verifies {_resourceIDToContractAddress}[{resourceID}] and
{_contractAddressToResourceID}[{contractAddress}] are not already set,
then sets {_resourceIDToContractAddress} with {contractAddress},
{_contractAddressToResourceID} with {resourceID},
{_contractAddressToDepositFunctionSignature} with {depositFunctionSig},
{_contractAddressToExecuteFunctionSignature} with {executeFunctionSig},
and {_contractWhitelist} to true for {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external override onlyBridge {
_setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice A deposit is initiatied by making a deposit in the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 64 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external onlyBridge {
bytes32 lenMetadata;
bytes memory metadata;
assembly {
// Load length of metadata from data + 64
lenMetadata := calldataload(0xC4)
// Load free memory pointer
metadata := mload(0x40)
mstore(0x40, add(0x20, add(metadata, lenMetadata)))
// func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) +
// bytes length (32) + resourceId (32) + length (32) = 0xC4
calldatacopy(
metadata, // copy to metadata
0xC4, // copy from calldata after metadata length declaration @0xC4
sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up))
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metadata);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
_depositRecords[destinationChainID][depositNonce] = DepositRecord(
destinationChainID,
depositer,
resourceID,
metadata
);
}
/**
@notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract.
@param data Consists of {resourceID}, {lenMetaData}, and {metaData}.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 32 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge {
bytes memory metaData;
assembly {
// metadata has variable length
// load free memory pointer to store metadata
metaData := mload(0x40)
// first 32 bytes of variable length in storage refer to length
let lenMeta := calldataload(0x64)
mstore(0x40, add(0x60, add(metaData, lenMeta)))
// in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params
calldatacopy(
metaData, // copy to metaData
0x64, // copy from calldata after data length declaration at 0x64
sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64)
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metaData);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
}
function _setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) internal {
_resourceIDToContractAddress[resourceID] = contractAddress;
_contractAddressToResourceID[contractAddress] = resourceID;
_contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig;
_contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig;
_contractWhitelist[contractAddress] = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/lib/contracts/libraries/FullMath.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
/**
* @title UniswapBroker
* @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual
* synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically
* swap and move a uniswap market.
*/
contract UniswapBroker {
using SafeMath for uint256;
/**
* @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as
* possible to the truePrice.
* @dev True price is expressed in the ratio of token A to token B.
* @dev The caller must approve this contract to spend whichever token is intended to be swapped.
* @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param uniswapFactory address of the uniswap factory used to fetch current pair reserves.
* @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure
* out which tokens need to be exchanged to move the market to the desired "true" price.
* @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price
* and the 1st value is the the denominator of the true price.
* @param maxSpendTokens array of unit to represent the max to spend in the two tokens.
* @param to recipient of the trade proceeds.
* @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert.
*/
function swapToPrice(
bool tradingAsEOA,
address uniswapRouter,
address uniswapFactory,
address[2] memory swappedTokens,
uint256[2] memory truePriceTokens,
uint256[2] memory maxSpendTokens,
address to,
uint256 deadline
) public {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]);
(aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB);
}
require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN");
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1];
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1];
address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0];
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests.
path,
to,
deadline
);
}
/**
* @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the
* uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move
* the pool price to be equal to the true price.
* @dev Note that this method uses the Babylonian square root method which has a small margin of error which will
* result in a small over or under estimation on the size of the trade needed.
* @param truePriceTokenA the nominator of the true price.
* @param truePriceTokenB the denominator of the true price.
* @param reserveA number of token A in the pair reserves
* @param reserveB number of token B in the pair reserves
*/
//
function computeTradeToMoveMarket(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) public pure returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
// The trade ∆a of token a required to move the market to some desired price P' from the current price P can be
// found with ∆a=(kP')^1/2-Ra.
uint256 leftSide =
Babylonian.sqrt(
FullMath.mulDiv(
invariant,
aToB ? truePriceTokenA : truePriceTokenB,
aToB ? truePriceTokenB : truePriceTokenA
)
);
uint256 rightSide = (aToB ? reserveA : reserveB);
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price back to the true price.
amountIn = leftSide.sub(rightSide);
}
// The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound
// to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so
// unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant
// handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker
// are simply moved here to maintain truffle support.
function getReserves(
address factory,
address tokenA,
address tokenB
) public view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// 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) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title ReserveCurrencyLiquidator
* @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of
* financial contracts. Is assumed to be called by a DSProxy which holds reserve currency.
*/
contract ReserveCurrencyLiquidator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to
* liquidate a position within one transaction.
* @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending
* liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has
* passed liveness. At this point the position can be manually unwound.
* @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted.
* These existing tokens will be used first before any swaps or mints are done.
* @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough
* collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param financialContract address of the financial contract on which the liquidation is occurring.
* @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy.
* @param liquidatedSponsor address of the sponsor to be liquidated.
* @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage.
* @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt.
* @param deadline abort the trade and liquidation if the transaction is mined after this timestamp.
**/
function swapMintLiquidate(
address uniswapRouter,
address financialContract,
address reserveCurrency,
address liquidatedSponsor,
FixedPoint.Unsigned calldata maxReserveTokenSpent,
FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
) public {
IFinancialContract fc = IFinancialContract(financialContract);
// 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already
// has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall).
FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc));
// 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics.
FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding());
FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr);
// 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any
// collateral needed to mint the token short fall.
FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall);
// 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this
// will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0.
FixedPoint.Unsigned memory collateralToBePurchased =
subOrZero(totalCollateralRequired, getCollateralBalance(fc));
// 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall.
// Note the path assumes a direct route from the reserve currency to the collateral currency.
if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
address[] memory path = new address[](2);
path[0] = reserveCurrency;
path[1] = fc.collateralCurrency();
TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue);
router.swapTokensForExactTokens(
collateralToBePurchased.rawValue,
maxReserveTokenSpent.rawValue,
path,
address(this),
deadline
);
}
// 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve
// or not enough collateral in the contract) the script should try to liquidate as much as it can regardless.
// Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall
// as the maximum tokens that could be liquidated at the current GCR.
if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) {
totalCollateralRequired = getCollateralBalance(fc);
collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc));
tokenShortfall = collateralToMintShortfall.divCeil(gcr);
}
// 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR.
// If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral
// currency as this is needed to pay the final fee in the liquidation tx.
TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue);
if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall);
// The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full
// token token balance at this point if there was a shortfall.
FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate;
if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc);
// 6. Liquidate position with newly minted synthetics.
TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue);
fc.createLiquidation(
liquidatedSponsor,
minCollateralPerTokenLiquidated,
maxCollateralPerTokenLiquidated,
liquidatableTokens,
deadline
);
}
// Helper method to work around subtraction overflow in the case of: a - b with b > a.
function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b)
internal
pure
returns (FixedPoint.Unsigned memory)
{
return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b);
}
// Helper method to return the current final fee for a given financial contract instance.
function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency());
}
// Helper method to return the collateral balance of this contract.
function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this)));
}
// Helper method to return the synthetic balance of this contract.
function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this)));
}
}
// Define some simple interfaces for dealing with UMA contracts.
interface IFinancialContract {
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
uint256 transferPositionRequestPassTimestamp;
}
function positions(address sponsor) external returns (PositionData memory);
function collateralCurrency() external returns (address);
function tokenCurrency() external returns (address);
function finder() external returns (address);
function pfc() external returns (FixedPoint.Unsigned memory);
function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory);
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external;
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
);
}
interface IStore {
function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory);
}
interface IFinder {
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
// Simple contract used to redeem tokens using a DSProxy from an emp.
contract TokenRedeemer {
function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens)
public
returns (FixedPoint.Unsigned memory)
{
IFinancialContract fc = IFinancialContract(financialContractAddress);
TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue);
return fc.redeem(numTokens);
}
}
interface IFinancialContract {
function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn);
function tokenCurrency() external returns (address);
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/VaultInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Mock for yearn-style vaults for use in tests.
*/
contract VaultMock is VaultInterface {
IERC20 public override token;
uint256 private pricePerFullShare = 0;
constructor(IERC20 _token) public {
token = _token;
}
function getPricePerFullShare() external view override returns (uint256) {
return pricePerFullShare;
}
function setPricePerFullShare(uint256 _pricePerFullShare) external {
pricePerFullShare = _pricePerFullShare;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Interface for Yearn-style vaults.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract VaultInterface {
// Return the underlying token.
function token() external view virtual returns (IERC20);
// Gets the number of return tokens that a "share" of this vault is worth.
function getPricePerFullShare() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Simple Perpetual Mock to serve trivial functions
*/
contract PerpetualMock {
struct FundingRate {
FixedPoint.Signed rate;
bytes32 identifier;
FixedPoint.Unsigned cumulativeMultiplier;
uint256 updateTime;
uint256 applicationTime;
uint256 proposalTime;
}
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
FundingRate public fundingRate;
// Interface functions required to be implemented in order for an instance of this contract to be passed into the
// off-chain FinancialContractClient helper module:
FixedPoint.Unsigned public collateralRequirement;
uint256 public liquidationLiveness;
FixedPoint.Unsigned public cumulativeFeeMultiplier;
mapping(address => uint256) public positions;
mapping(address => uint256) public liquidations;
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition();
event LiquidationCreated();
function getCurrentTime() public view returns (uint256) {
return now;
}
// Public methods that are useful for tests:
function setFundingRate(FundingRate memory _fundingRate) external {
fundingRate = _fundingRate;
}
function applyFundingRate() external {
fundingRate.applicationTime = block.timestamp;
// Simplified rate calcualtion.
// multiplier = multiplier * (1 + rate)
fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul(
FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate))
);
}
}
|
Whether `a` is less than or equal to `b`. a a FixedPoint.Signed. b an int256. return True if `a <= b`, or False./
|
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
| 98,898 |
./full_match/1/0x423f4e6138E475D85CF7Ea071AC92097Ed631eea/sources/contracts/Pondclaims.sol
|
Verify that all lengths match
|
function canClaim(
address[] calldata addresses,
uint256[] calldata amounts,
uint32[] calldata offsets,
bytes32[][] calldata merkleProofs
) external view returns (bool[] memory) {
uint length = addresses.length;
require(amounts.length == length && offsets.length == length && merkleProofs.length == length, "Invalid Lengths");
bool[] memory statuses = new bool[](length);
for (uint256 i = 0; i < length; i++) {
statuses[i] = _canClaim(addresses[i], amounts[i], offsets[i], merkleProofs[i]);
}
return (statuses);
}
| 17,144,789 |
/*
⚠⚠⚠ WARNING WARNING WARNING ⚠⚠⚠
This is a TARGET contract - DO NOT CONNECT TO IT DIRECTLY IN YOUR CONTRACTS or DAPPS!
This contract has an associated PROXY that MUST be used for all integrations - this TARGET will be REPLACED in an upcoming Synthetix release!
The proxy can be found by looking up the PROXY property on this contract.
*//*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: Synth.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/Synth.sol
* Docs: https://docs.synthetix.io/contracts/Synth
*
* Contract Dependencies:
* - ExternStateToken
* - IAddressResolver
* - IERC20
* - ISynth
* - MixinResolver
* - Owned
* - Proxyable
* - State
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* 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
*/
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_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 {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/proxy
contract Proxy is Owned {
Proxyable public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(Proxyable _target) external onlyOwner {
target = _target;
emit TargetUpdated(_target);
}
function _emit(
bytes calldata 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)
}
}
}
// solhint-disable no-complex-fallback
function() external payable {
// Mutable call setting Proxyable.messageSender as this is using call not 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, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/proxyable
contract Proxyable is Owned {
// This contract should be treated like an abstract contract
/* The proxy this contract exists behind. */
Proxy public proxy;
Proxy public integrationProxy;
/* 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 public messageSender;
constructor(address payable _proxy) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address payable _proxy) external onlyOwner {
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setIntegrationProxy(address payable _integrationProxy) external onlyOwner {
integrationProxy = Proxy(_integrationProxy);
}
function setMessageSender(address sender) external onlyProxy {
messageSender = sender;
}
modifier onlyProxy {
_onlyProxy();
_;
}
function _onlyProxy() private view {
require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call");
}
modifier optionalProxy {
_optionalProxy();
_;
}
function _optionalProxy() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
}
modifier optionalProxy_onlyOwner {
_optionalProxy_onlyOwner();
_;
}
// solhint-disable-next-line func-name-mixedcase
function _optionalProxy_onlyOwner() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
require(messageSender == owner, "Owner only function");
}
event ProxyUpdated(address proxyAddress);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// 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;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @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. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/state
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 _associatedContract) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
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);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/tokenstate
contract TokenState is Owned, State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== 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;
}
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/externstatetoken
contract ExternStateToken is Owned, Proxyable {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields. */
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _name,
string memory _symbol,
uint _totalSupply,
uint8 _decimals,
address _owner
) public Owned(_owner) Proxyable(_proxy) {
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
/* ========== 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) external 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(address(_tokenState));
}
function _internalTransfer(
address from,
address to,
uint value
) internal returns (bool) {
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address");
// Insufficient balance will be handled by the safe subtraction.
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(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 _transferByProxy(
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 _transferFromByProxy(
address sender,
address from,
address to,
uint value
) internal returns (bool) {
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(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 ========== */
function addressToBytes32(address input) internal pure returns (bytes32) {
return bytes32(uint256(uint160(input)));
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 internal 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, addressToBytes32(from), addressToBytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 internal 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, addressToBytes32(owner), addressToBytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.synthetix.io/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination = resolver.requireAndGetAddress(
name,
string(abi.encodePacked("Resolver missing target: ", name))
);
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
interface IVirtualSynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function synth() external view returns (ISynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external;
function suspendSynthWithInvalidRate(bytes32 currencyKey) external;
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/synth
contract Synth is Owned, IERC20, ExternStateToken, MixinResolver, ISynth {
/* ========== STATE VARIABLES ========== */
// Currency key which identifies this Synth to the Synthetix system
bytes32 public currencyKey;
uint8 public constant DECIMALS = 18;
// Where fees are pooled in sUSD
address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
/* ========== CONSTRUCTOR ========== */
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _tokenName,
string memory _tokenSymbol,
address _owner,
bytes32 _currencyKey,
uint _totalSupply,
address _resolver
)
public
ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner)
MixinResolver(_resolver)
{
require(_proxy != address(0), "_proxy cannot be 0");
require(_owner != address(0), "_owner cannot be 0");
currencyKey = _currencyKey;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function transfer(address to, uint value) public optionalProxy returns (bool) {
_ensureCanTransfer(messageSender, value);
// transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee
if (to == FEE_ADDRESS) {
return _transferToFeeAddress(to, value);
}
// transfers to 0x address will be burned
if (to == address(0)) {
return _internalBurn(messageSender, value);
}
return super._internalTransfer(messageSender, to, value);
}
function transferAndSettle(address to, uint value) public optionalProxy returns (bool) {
// Exchanger.settle ensures synth is active
(, , uint numEntriesSettled) = exchanger().settle(messageSender, currencyKey);
// Save gas instead of calling transferableSynths
uint balanceAfter = value;
if (numEntriesSettled > 0) {
balanceAfter = tokenState.balanceOf(messageSender);
}
// Reduce the value to transfer if balance is insufficient after reclaimed
value = value > balanceAfter ? balanceAfter : value;
return super._internalTransfer(messageSender, to, value);
}
function transferFrom(
address from,
address to,
uint value
) public optionalProxy returns (bool) {
_ensureCanTransfer(from, value);
return _internalTransferFrom(from, to, value);
}
function transferFromAndSettle(
address from,
address to,
uint value
) public optionalProxy returns (bool) {
// Exchanger.settle() ensures synth is active
(, , uint numEntriesSettled) = exchanger().settle(from, currencyKey);
// Save gas instead of calling transferableSynths
uint balanceAfter = value;
if (numEntriesSettled > 0) {
balanceAfter = tokenState.balanceOf(from);
}
// Reduce the value to transfer if balance is insufficient after reclaimed
value = value >= balanceAfter ? balanceAfter : value;
return _internalTransferFrom(from, to, value);
}
/**
* @notice _transferToFeeAddress function
* non-sUSD synths are exchanged into sUSD via synthInitiatedExchange
* notify feePool to record amount as fee paid to feePool */
function _transferToFeeAddress(address to, uint value) internal returns (bool) {
uint amountInUSD;
// sUSD can be transferred to FEE_ADDRESS directly
if (currencyKey == "sUSD") {
amountInUSD = value;
super._internalTransfer(messageSender, to, value);
} else {
// else exchange synth into sUSD and send to FEE_ADDRESS
amountInUSD = exchanger().exchange(messageSender, currencyKey, value, "sUSD", FEE_ADDRESS);
}
// Notify feePool to record sUSD to distribute as fees
feePool().recordFeePaid(amountInUSD);
return true;
}
function issue(address account, uint amount) external onlyInternalContracts {
_internalIssue(account, amount);
}
function burn(address account, uint amount) external onlyInternalContracts {
_internalBurn(account, amount);
}
function _internalIssue(address account, uint amount) internal {
tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
totalSupply = totalSupply.add(amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
function _internalBurn(address account, uint amount) internal returns (bool) {
tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
totalSupply = totalSupply.sub(amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
return true;
}
// Allow owner to set the total supply on import.
function setTotalSupply(uint amount) external optionalProxy_onlyOwner {
totalSupply = amount;
}
/* ========== VIEWS ========== */
// Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](4);
addresses[0] = CONTRACT_SYSTEMSTATUS;
addresses[1] = CONTRACT_EXCHANGER;
addresses[2] = CONTRACT_ISSUER;
addresses[3] = CONTRACT_FEEPOOL;
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function _ensureCanTransfer(address from, uint value) internal view {
require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period");
require(transferableSynths(from) >= value, "Insufficient balance after any settlement owing");
systemStatus().requireSynthActive(currencyKey);
}
function transferableSynths(address account) public view returns (uint) {
(uint reclaimAmount, , ) = exchanger().settlementOwing(account, currencyKey);
// Note: ignoring rebate amount here because a settle() is required in order to
// allow the transfer to actually work
uint balance = tokenState.balanceOf(account);
if (reclaimAmount > balance) {
return 0;
} else {
return balance.sub(reclaimAmount);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _internalTransferFrom(
address from,
address to,
uint value
) internal returns (bool) {
// Skip allowance update in case of infinite allowance
if (tokenState.allowance(from, messageSender) != uint(-1)) {
// Reduce the allowance by the amount we're transferring.
// The safeSub call will handle an insufficient allowance.
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
}
return super._internalTransfer(from, to, value);
}
/* ========== MODIFIERS ========== */
modifier onlyInternalContracts() {
bool isFeePool = msg.sender == address(feePool());
bool isExchanger = msg.sender == address(exchanger());
bool isIssuer = msg.sender == address(issuer());
require(isFeePool || isExchanger || isIssuer, "Only FeePool, Exchanger or Issuer contracts allowed");
_;
}
/* ========== EVENTS ========== */
event Issued(address indexed account, uint value);
bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, ISSUED_SIG, addressToBytes32(account), 0, 0);
}
event Burned(address indexed account, uint value);
bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, BURNED_SIG, addressToBytes32(account), 0, 0);
}
}
|
Views Restricted functions https:docs.synthetix.io/contracts/source/interfaces/ifeepool Views solhint-disable-next-line func-name-mixedcase Mutative Functions Restricted: used internally to Synthetix
|
interface IFeePool {
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
| 84,651 |
pragma solidity >=0.5.4 <0.6.0;
import './AOLibrary.sol';
import './TheAO.sol';
import './IAOSetting.sol';
import './INameFactory.sol';
import './IAOSettingAttribute.sol';
import './IAOSettingValue.sol';
import './INameTAOPosition.sol';
import './INameAccountRecovery.sol';
/**
* @title AOSetting
*
* This contract stores all AO setting variables
*/
contract AOSetting is TheAO, IAOSetting {
address public nameFactoryAddress;
address public nameAccountRecoveryAddress;
address public aoSettingAttributeAddress;
address public aoSettingValueAddress;
INameFactory internal _nameFactory;
INameTAOPosition internal _nameTAOPosition;
INameAccountRecovery internal _nameAccountRecovery;
IAOSettingAttribute internal _aoSettingAttribute;
IAOSettingValue internal _aoSettingValue;
uint8 constant public ADDRESS_SETTING_TYPE = 1;
uint8 constant public BOOL_SETTING_TYPE = 2;
uint8 constant public BYTES_SETTING_TYPE = 3;
uint8 constant public STRING_SETTING_TYPE = 4;
uint8 constant public UINT_SETTING_TYPE = 5;
uint256 public totalSetting;
/**
* Mapping from associatedTAOId's setting name to Setting ID.
*
* Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup,
* use nested mapping to achieve the same result.
*
* The setting's name needs to be converted to bytes32 since solidity does not support mapping by string.
*/
mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup;
// Mapping from updateHashKey to it's settingId
mapping (bytes32 => uint256) public updateHashLookup;
// Mapping from setting ID to it's type
// setting type 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
mapping (uint256 => uint8) internal _settingTypeLookup;
// Event to be broadcasted to public when a setting is created and waiting for approval
event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId);
// Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId
event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress,
address _nameTAOPositionAddress,
address _nameAccountRecoveryAddress,
address _aoSettingAttributeAddress,
address _aoSettingValueAddress
) public {
setNameFactoryAddress(_nameFactoryAddress);
setNameTAOPositionAddress(_nameTAOPositionAddress);
setNameAccountRecoveryAddress(_nameAccountRecoveryAddress);
setAOSettingAttributeAddress(_aoSettingAttributeAddress);
setAOSettingValueAddress(_aoSettingValueAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_settingName` of `_associatedTAOId` is taken
*/
modifier settingNameNotTaken(string memory _settingName, address _associatedTAOId) {
require (settingNameExist(_settingName, _associatedTAOId) == false);
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Only allowed if sender's Name is not compromised
*/
modifier senderNameNotCompromised() {
require (!_nameAccountRecovery.isCompromised(_nameFactory.ethAddressToNameId(msg.sender)));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO sets NameFactory address
* @param _nameFactoryAddress The address of NameFactory
*/
function setNameFactoryAddress(address _nameFactoryAddress) public onlyTheAO {
require (_nameFactoryAddress != address(0));
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = INameFactory(_nameFactoryAddress);
}
/**
* @dev The AO sets NameTAOPosition address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = INameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev The AO set the NameAccountRecovery Address
* @param _nameAccountRecoveryAddress The address of NameAccountRecovery
*/
function setNameAccountRecoveryAddress(address _nameAccountRecoveryAddress) public onlyTheAO {
require (_nameAccountRecoveryAddress != address(0));
nameAccountRecoveryAddress = _nameAccountRecoveryAddress;
_nameAccountRecovery = INameAccountRecovery(nameAccountRecoveryAddress);
}
/**
* @dev The AO sets AOSettingAttribute address
* @param _aoSettingAttributeAddress The address of AOSettingAttribute
*/
function setAOSettingAttributeAddress(address _aoSettingAttributeAddress) public onlyTheAO {
require (_aoSettingAttributeAddress != address(0));
aoSettingAttributeAddress = _aoSettingAttributeAddress;
_aoSettingAttribute = IAOSettingAttribute(_aoSettingAttributeAddress);
}
/**
* @dev The AO sets AOSettingValue address
* @param _aoSettingValueAddress The address of AOSettingValue
*/
function setAOSettingValueAddress(address _aoSettingValueAddress) public onlyTheAO {
require (_aoSettingValueAddress != address(0));
aoSettingValueAddress = _aoSettingValueAddress;
_aoSettingValue = IAOSettingValue(_aoSettingValueAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a setting name of an associatedTAOId exist
* @param _settingName The human-readable name of the setting
* @param _associatedTAOId The taoId that the setting affects
* @return true if yes. false otherwise
*/
function settingNameExist(string memory _settingName, address _associatedTAOId) public view returns (bool) {
return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0);
}
/**
* @dev Advocate of _creatorTAOId adds a uint setting
* @param _settingName The human-readable name of the setting
* @param _value The uint256 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addUintSetting(
string memory _settingName,
uint256 _value,
address _creatorTAOId,
address _associatedTAOId,
string memory _extraData)
public
isTAO(_creatorTAOId)
isTAO(_associatedTAOId)
settingNameNotTaken(_settingName, _associatedTAOId)
onlyAdvocate(_creatorTAOId)
senderNameNotCompromised {
// Update global variables
totalSetting++;
_settingTypeLookup[totalSetting] = UINT_SETTING_TYPE;
// Store the value as pending value
_aoSettingValue.setPendingValue(totalSetting, address(0), false, '', '', _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bool setting
* @param _settingName The human-readable name of the setting
* @param _value The bool value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBoolSetting(
string memory _settingName,
bool _value,
address _creatorTAOId,
address _associatedTAOId,
string memory _extraData)
public
isTAO(_creatorTAOId)
isTAO(_associatedTAOId)
settingNameNotTaken(_settingName, _associatedTAOId)
onlyAdvocate(_creatorTAOId)
senderNameNotCompromised {
// Update global variables
totalSetting++;
_settingTypeLookup[totalSetting] = BOOL_SETTING_TYPE;
// Store the value as pending value
_aoSettingValue.setPendingValue(totalSetting, address(0), _value, '', '', 0);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds an address setting
* @param _settingName The human-readable name of the setting
* @param _value The address value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addAddressSetting(
string memory _settingName,
address _value,
address _creatorTAOId,
address _associatedTAOId,
string memory _extraData)
public
isTAO(_creatorTAOId)
isTAO(_associatedTAOId)
settingNameNotTaken(_settingName, _associatedTAOId)
onlyAdvocate(_creatorTAOId)
senderNameNotCompromised {
// Update global variables
totalSetting++;
_settingTypeLookup[totalSetting] = ADDRESS_SETTING_TYPE;
// Store the value as pending value
_aoSettingValue.setPendingValue(totalSetting, _value, false, '', '', 0);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bytes32 setting
* @param _settingName The human-readable name of the setting
* @param _value The bytes32 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBytesSetting(
string memory _settingName,
bytes32 _value,
address _creatorTAOId,
address _associatedTAOId,
string memory _extraData)
public
isTAO(_creatorTAOId)
isTAO(_associatedTAOId)
settingNameNotTaken(_settingName, _associatedTAOId)
onlyAdvocate(_creatorTAOId)
senderNameNotCompromised {
// Update global variables
totalSetting++;
_settingTypeLookup[totalSetting] = BYTES_SETTING_TYPE;
// Store the value as pending value
_aoSettingValue.setPendingValue(totalSetting, address(0), false, _value, '', 0);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a string setting
* @param _settingName The human-readable name of the setting
* @param _value The string value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addStringSetting(
string memory _settingName,
string memory _value,
address _creatorTAOId,
address _associatedTAOId,
string memory _extraData)
public
isTAO(_creatorTAOId)
isTAO(_associatedTAOId)
settingNameNotTaken(_settingName, _associatedTAOId)
onlyAdvocate(_creatorTAOId)
senderNameNotCompromised {
// Update global variables
totalSetting++;
_settingTypeLookup[totalSetting] = STRING_SETTING_TYPE;
// Store the value as pending value
_aoSettingValue.setPendingValue(totalSetting, address(0), false, '', _value, 0);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingCreation(uint256 _settingId, bool _approved) public senderIsName senderNameNotCompromised {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved));
(,,, address _associatedTAOId, string memory _settingName,,,,) = _aoSettingAttribute.getSettingData(_settingId);
if (!_approved) {
// Clear the settingName from nameSettingLookup so it can be added again in the future
delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
delete _settingTypeLookup[_settingId];
}
emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingCreation(uint256 _settingId) public senderIsName senderNameNotCompromised {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate));
(,,address _creatorTAOId,,,,,,) = _aoSettingAttribute.getSettingData(_settingId);
require (_aoSettingValue.movePendingToSetting(_settingId));
emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Get setting type of a setting ID
* @param _settingId The ID of the setting
* @return the setting type value
* setting type 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
*/
function settingTypeLookup(uint256 _settingId) external view returns (uint8) {
return _settingTypeLookup[_settingId];
}
/**
* @dev Get setting Id given an associatedTAOId and settingName
* @param _associatedTAOId The ID of the AssociatedTAO
* @param _settingName The name of the setting
* @return the ID of the setting
*/
function getSettingIdByTAOName(address _associatedTAOId, string memory _settingName) public view returns (uint256) {
return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
/**
* @dev Get setting values by setting ID.
* Will throw error if the setting is not exist or rejected.
* @param _settingId The ID of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string memory) {
require (_aoSettingAttribute.settingExist(_settingId));
_settingId = _aoSettingAttribute.getLatestSettingId(_settingId);
(address _addressValue, bool _boolValue, bytes32 _bytesValue, string memory _stringValue, uint256 _uintValue) = _aoSettingValue.settingValue(_settingId);
return (_uintValue, _boolValue, _addressValue, _bytesValue, _stringValue);
}
/**
* @dev Get setting values by taoId and settingName.
* Will throw error if the setting is not exist or rejected.
* @param _taoId The ID of the TAO
* @param _settingName The name of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesByTAOName(address _taoId, string calldata _settingName) external view returns (uint256, bool, address, bytes32, string memory) {
return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName));
}
/**
* @dev Return the setting type values
* @return The setting type value for address
* @return The setting type value for bool
* @return The setting type value for bytes
* @return The setting type value for string
* @return The setting type value for uint
*/
function getSettingTypes() external view returns (uint8, uint8, uint8, uint8, uint8) {
return (
ADDRESS_SETTING_TYPE,
BOOL_SETTING_TYPE,
BYTES_SETTING_TYPE,
STRING_SETTING_TYPE,
UINT_SETTING_TYPE
);
}
/***** Internal Method *****/
/**
* @dev Store setting creation data
* @param _creatorNameId The nameId that created the setting
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function _storeSettingCreation(address _creatorNameId, string memory _settingName, address _creatorTAOId, address _associatedTAOId, string memory _extraData) internal {
// Store nameSettingLookup
nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(address(this), _settingName))] = totalSetting;
// Store setting data/state
(bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _associatedTAOSettingId, _creatorTAOSettingId);
}
}
|
Advocate of _creatorTAOId adds a bool setting _settingName The human-readable name of the setting _value The bool value of the setting _creatorTAOId The taoId that created the setting _associatedTAOId The taoId that the setting affects _extraData Catch-all string value to be stored if exist/ Update global variables Store the value as pending value Store setting creation data
|
function addBoolSetting(
string memory _settingName,
bool _value,
address _creatorTAOId,
address _associatedTAOId,
string memory _extraData)
public
isTAO(_creatorTAOId)
isTAO(_associatedTAOId)
settingNameNotTaken(_settingName, _associatedTAOId)
onlyAdvocate(_creatorTAOId)
senderNameNotCompromised {
totalSetting++;
_settingTypeLookup[totalSetting] = BOOL_SETTING_TYPE;
_aoSettingValue.setPendingValue(totalSetting, address(0), _value, '', '', 0);
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
| 2,518,417 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
/*
Basically this is supposed to be a smart contract that self-regulates masterchef
Inflation is pre-determined with this contract...
It can also be modified "on-chain" by "voting"
1.)WE START AT reward of 25/block
2.) After 22september anyone can call a function that increases rewards(updates masterchef rewards) to 100
called "rapid adoption boost/phase"
3.) Then there are events which anyone can call, on each function call, the reward per block reduces by Golden Ratio(updates to masterchef)
Function can be called:
First every 4 hours (x18)
Then every 6hours (12x)
Then every 8hours (9x)
Then every 12hours (7x)
Then set inflation back to 25/block
Basically what it does is it gives an initial boost to 100/block and reduces it each time period towards 25
4.) on 23rd of November, print like 23.6% of whole supply in 48hours ("big fibonaci payout")
Need to calculate average block time for this.
5.) reduce inflation to 25/block and from there on we are going down per golden ratio on each one
6.) Start "automatic governance"
7.) 3 functions
Initiate and Veto should require an amount of tokens to be "deposited" as a cost for calling the contract and those funds should be burned
//either burned, or just kept by the contract is okay too i guess
Initiate: proposal is pushed into array
Veto: proposal can be voted against(negated)
Execute; if it's not voted against in a period of time, it can be enforced
8.) there are also 3 functions that regulate the rewards for XVMC-USDC, XVMC-WMATIC and DOGE2 pool(poolID 0,1 and 11)
max for doge2 is 5%, and 4% for pool 0 and 1 collectively
has to also be proposed... for each.
8.) When block reward goes to roughly 1.6(it will have to reduce like 15-16times by 1.6 each time from 25 to 1.618),
"The grand fibonaccenning" happens, where supply inflates up to a 1,000,000X
in that time period (creates a total supply of a quadrillion 1,000,000,000,000,000) and sets the
inflation to a golden ratio(in % on annual basis)So basically 1.618% annual inflation.
I think the best way would be to just do a basic exponent function. Basically multiply supply by 1.618X on each event and you
need around 25-30 events. The inflation boost should happen in a period of 7-14 days.
There should be long breaks, and then BIG inflation, rapidly, and then break again(you don't want constant rewards over that period
because if people bought, they would get diluted badly on inflation very quickly).
During those 7-14days, set rewards to 0 for 12hours, then print for 30minutes(until supplies goes x1.618), rest 12hours, repeat,
or something similar...
9.) DO WE NEED TO CREATE PAUSABLE FUNCTION(in autocompounding pool - prevent autocompounding during that period?)
when grand fibonaccening and second is how does 130% work over the long term compounded ??
*/
//how will auto-compounding effect during "Grand Fibonaccening" if one pool receives 1,3x, how does this
// play out during those events where massive amount is printed?
//do we need to add stop auto-compounding durnig those events?
// i don't know solidity, this is just a concept... for the explanation above
/// @notice Owner address
address owner;
int immutable goldenRatio = 1.6180339887 * 1e18; //The golden ratio, the sacred number, do we need e18 or no? WHEN??
int EVMnumberFormat = 1e18;
address immutable ourERCtokenAddress = "0x....."; //our ERC20 token contract address
address immutable deadAddress = "0x000000000000000000000000000000000000dead"; //dead address
int immutable minimum = 1000; //unchangeable, forever min 1000
//can be changed, but not less than minimum. This is the tokens that must be sacrificed in order to "vote"
//voting should be affordable, but a minimum is required to prevent spam
int costToVote = 1000;
//proposals to change costToVote, stored in 2-dimensiona array
proposalMinDeposit[id][[boolean], [firstCallTimestamp], [valueSacrificedForVote], [value]];
//should we set immutable delaybefore enforce like 1day? gives minimum 1 day before proposals can be activated?? HMH idk!
int delayBeforeEnforce = 44000; //minimum number of blocks between when costToVote is proposed and executed
struct proposeDelayBeforeEnforce {
bool valid;
int firstCallTimestamp;
int proposedValue;
}
proposeDelayBeforeEnforcel[] public delayProposals;
boolean gracePeriodActivation = false; //if grace period has been requested
int timestampGracePeriod; //timestamp of grace period
int immutable minThresholdFibonaccening = 1000000;
int thresholdFibonnacening = 5000000;
struct proposalThresholdFibonnacening {
bool valid;
int proposedValue;
int proposedDuration;
int firstCallTimestamp;
}
proposalThresholdFibonnacening[] public proposalThresholdFibonnaceningList; //i don't know syntax for this, is it right?
//delays for Fibonnaccenning Events
int immutable minDelay = 1days; // has to be called minimum 1 day in advance
int immutable maxDelay = 31 days; //1month.. is that good? i think yes
int currentDelay = 3days;
//remember the reward prior to updating so it can be reverted
int rewardPerBlockPriorFibonaccening;
bool eventFibonacceningActive = false; // prevent some functions if event is active ..threshold and durations for fibonaccening
bool expiredGrandFibonaccenning = false;
//fibonacci proposals. When enough penalties are collected, inflation is reduced by golden ratio.
struct fibonaccenningProposal {
bool valid;
int firstCallTimestamp;
int valueSacrificedForVote;
int multiplier;
int currentDelay;
int duration;
}
fibonaccenningProposal[] public fibonaccenningProposalList;
bool handsOff = false;
//by default paused/handsoff is turned on. The inflation should run according to schedule, until after the Big Fibonnaci day
//functions and voting is turned on during that period, immutable
int preProgrammedCounter = 46; //we reduce inflation by golden ratio 35 time
int preProgrammedCounterTimestamp = 0;
bool rapidAdoptionBoost = false; //can only be called once, after 22 september
bool bigFibonaciActivated = false;
bool bigFibonaciStopped = false;
int blocksPerSecond = 2.5;
int durationForCalculation= 12hours; //make this changeable(voteable) BUT NOT WEN COUNTING BLOCKS active!
int lastBlockHeight = 0;
int recordTimeStart;
bool countingBlocks = false;
struct proposalDurationForCalculation {
bool valid;
int duration;
int tokensSacrificedForVoting;
int firstCallTimestamp;
}
proposalDurationForCalculation[] public proposeDurationCalculation;
//need this or not IDK?
int circulatingSupply;
int maximumVoteTokens;
//in case block times change over the long run, this function can be used to rebalance
//only start counting them
int totalFibonaciEventsAfterGrand = 0;
struct proposalRebalanceInflation {
bool valid; //if it remains true, it can be called
int tokensSacrificedForVoting;
int firstCallTimestamp;
}
proposalRebalanceInflation[] public rebalanceProposals;
function initiateRebalanceProposal(int depositingTokensn) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
rebalanceProposals.push("true", depositingTokens, firstCallTimestamp); //submit new proposal
}
//reject if proposal is invalid(false), and if the required delay since last call and first call have not been met
function executeRebalanceProposal(int proposalID) {
if(rebalanceProposals[proposalID][0] == false || proposeDurationCalculation[proposalID][2] < (block.timestamp + delayBeforeEnforce)) { reject }
rebalanceInflation(proposalID);
rebalanceProposals[proposalID][0] = false;
}
function vetoRebalanceProposal(int proposalID, int depositingTokens) {
if (rebalanceProposals[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != rebalanceProposals[proposalID][1]) { reject "must match amount to veto"; }
rebalanceProposals[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//there should be valid proposalID to do so tbh
//this rebalances inflation to Golden ratio(and number of fibonacennings afterward)
function rebalanceInflation(int proposalID) {
if(totalFibonaciEventsAfterGrand == 0) { reject "only works after grand fibonaccening" }
if(!rebalanceProposals[proposalID][0]) { reject "proposal is invalid" }
//rebalance inflation to
setInflation(getTotalSupply() * (((100 - goldenRatio)/100)exponent totalFibonaciEventsAfterGrand));
}
//can't use more than 0.1% of circulating supply to vote, making sure to prevent tyranny and always potentially veto
//US presidentials cost approximately 0.0133% of total US worth. This is crypto so let's give little more space
//in all proposals you can't deposit more than this amount of tokens
function updateMaximumVoteTokens {
maximumVoteTokens = getTotalSupply() * 0.0005;
}
function updateCirculatingSupply(){
circulatingSupply = getTotalSupply();
}
//after counting is done, updated into database the numberino
function calculateAverageBlockTime() {
if(countingBlocks && (recordTimeStart + durationForCalculation) >= block.timestamp) {
blocksPerSecond = (block.height - lastBlockHeight) / durationForCalculation(must be in seconds); //gets number of blocks per second
countingBlocks = false;
}
}
//can be called by anybody because it doesn't have any real impact
function startCountingBlocks(){
require(!countingBlocks) { "already counting blocks" }
countingBlocks = true;
lastBlockHeight = block.height; //remember block number height
recordTimeStart = block.time; //remember time
}
//shit doesn't really matter cuz after big fibonnaci daz we go down to 25-golden ratio, so need not to remember until then
function rapidAdoptionBoost() public {
if(rapidAdoptionBoost) { reject "already been activated"; }
if(block.timestamp < 22.september) { reject "rapidAdoptionBoost can only be activated after this period" }
rapidAdoptionBoost = true;
}
function updatePreProgrammedRewards() public anyone1 can call {
if(!rapidAdoptionBoost) { reject "programIsOff"; } //not sure which one is the right one now
if(preProgrammedCounter == 46) {
setInflation(100 * EVMnumberFormat);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter < 46 && lastPreProgrammedCounter > 27) {
if(preProgrammedCounterTimestamp + 5760 < block.timestamp) { reject "delay not met, must wait 4hrs"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(rewardPerBlockPriorFibonaccening);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter < 28 && lastPreProgrammedCounter > 14) {
if(preProgrammedCounterTimestamp + 8640 < block.timestamp) { reject "delay not met, must wait 6hrs"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(rewardPerBlockPriorFibonaccening);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter < 15 && lastPreProgrammedCounter > 4) {
if(preProgrammedCounterTimestamp + 11520 < block.timestamp) { reject "delay not met, must wait 8hrs"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(rewardPerBlockPriorFibonaccening);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter < 5 && lastPreProgrammedCounter > 1) {
if(preProgrammedCounterTimestamp + 8640 < block.timestamp) { reject "delay not met, must wait 12hrs"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(rewardPerBlockPriorFibonaccening);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter == 1) {
if(preProgrammedCounterTimestamp + 17280 < block.timestamp) { reject "delay not met, must wait 1day"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(25000000000000000000); // set to 25XVMC/block
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
//inflation goes to 25XVMC block, rapidadoption boost can't be activated ever again and the counter can't go above 0 again either
}
}
//Big fibonnaci day, 23.8% of supply printed in a period of 48hours, then revert to 25XVMC/block and on-chain governance
//anyone can call this
function bigFibonaciPayout() {
//function can be called 12hours prior to the day UTC, and expires 12hours after, total 48hours duration
if(!bigFibonaciActivated && block.timestamp >(12hourspprior23november)) { //activate big fibonaci day
bigFibonaciActivated = true;
//calculate rewards, need a function that gets blocks
setInflation((getTotalSupply()*0.236) / (48 * 3600 / blocksPerSecond));
// 23.6% of total supply must be printed in 48hours,s o reward per second should be totalsupply*0.236 / 48hoursinseconds
//halt other functions as to not mess up? IDK!!
}
}
bool endBigFibonaciDay = false;
function endBigFibonaciPayout() {
require(bigFibonaciActivated && !endBigFibonaciDay) { "can't activated if not ongoing" })
require(block.timestamp > 12hoursafter23november) { "must last 24hours" }
//must be active and must expire and must not be callable again function
setInflation(25000000000000000000); // set to 25tokens/block
rewardPerBlockPriorFibonaccening = 25000000000000000000;
endBigFibonaciDay = true;
}
struct proposalFarm {
bool valid;
int poolid;
int newAllocation;
int tokensSacrificedForVoting;
int firstCallTimestamp;
}
proposalFarm[] public proposalFarmUpdate;
function initiateFarmProposal(int depositingTokens, int poolid, int newAllocation[]) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
if(poolid !(in_array([0,1,11]))) { "reject, only allowed for these pools" }
if(poolid == 11 && newAllocation > 5000) { reject "max 5k" }
//you can propose any amount but it will not get accepted by updateFarms anyways
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposalFarmUpdate.push("true", poolid, newAllocation, depositingTokens, firstCallTimestamp); //submit new proposal
}
function vetoFarmProposal(int proposalID, int depositingTokens) {
if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != proposalFarmUpdate[proposalID][3]) { reject "must match amount to veto"; }
proposalFarmUpdate[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//updateFarms actually acts akin to the execute Proposal in this case
//this is to update farm and pool allocations,which can be proposed
int allocationPool1 = XX; //SET THIS AT BEGINNING
int allocationPool2 = XX;
int immutable maxFarmRewards = 1000; //idk the actual number, set this shit broski..but this is not locked so welp fuck
function updateFarm0(int proposalID, int massUpdate) {
if(proposalFarmUpdate[proposalID][0] = "false"( { reject "not valid proposal"})
if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"}
if(allocationPool2 + proposalFarmUpdate[proposalID][2] > maxFarmRewards) { reject "exceeding max" }
updatePool(0, newAllocationPool1, massUpdate);;
}
function updateFarm1(int proposalID, int massUpdate) {
if(proposalFarmUpdate[proposalID][0] = "false"( { reject "not valid proposal"})
if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"}
if(allocationPool1 + proposalFarmUpdate[proposalID][2] > maxFarmRewards) { reject "exceeding max" }
updatePool(1, newAllocationPool2, massUpdate);
}
//poolid preset to 11
function updateFarm11(int massUpdate, int proposalID) {
if(proposalFarmUpdate[proposalID][0] = "false"( { rject "not valid proposal"})
if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"}
//need proposal
updatePool(11, newAllocation, massUpdate);
}
function initiateDelayProposal(int depositingTokens, int duration) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposeDurationCalculation.push("true", duration, depositingTokens, firstCallTimestamp); //submit new proposal
}
//reject if proposal is invalid(false), and if the required delay since last call and first call have not been met
function executeDelayProposal(int proposalID) {
if(proposeDurationCalculation[proposalID][0] == false || proposeDurationCalculation[proposalID][3] < (block.timestamp + delayBeforeEnforce)) { reject }
durationForCalculation = proposeDurationCalculation[proposalID][1]; // enforce new rule
proposeDurationCalculation[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too)
}
function vetoDelayProposal(int proposalID, int depositingTokens) {
if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != proposeDurationCalculation[proposalID][2]) { reject "must match amount to veto"; }
proposeDurationCalculation[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
function initiateProposalDurationForCalculation(int depositingTokens, int duration) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposeDurationCalculation.push("true", duration, depositingTokens, firstCallTimestamp); //submit new proposal
}
//reject if proposal is invalid(false), and if the required delay since last call and first call have not been met
function executeProposalDurationForCalculation(int proposalID) {
if(proposeDurationCalculation[proposalID][0] == false || proposeDurationCalculation[proposalID][3] < (block.timestamp + delayBeforeEnforce)) { reject }
durationForCalculation = proposeDurationCalculation[proposalID][1]; // enforce new rule
proposeDurationCalculation[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too)
}
function vetoProposalDurationForCalculation(int proposalID, int depositingTokens) {
if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != proposeDurationCalculation[proposalID][2]) { reject "must match amount to veto"; }
proposeDurationCalculation[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//fibonaccenning function determines by how much the reward per block is reduced
//prior to the "grand fibonaccenning" event, the reward per block is deducted by the golden ratio
//on the big event, reward per block is set to the golden ratio (totalsupply * 0.01618) AKA 1.6180%/ANNUALLY
//after the big event, reward per block is reduced by a golden number in percentage = (previous * ((100-1.6180)/100))
function calculateFibonaccenningNewRewardPerBlock() {
if(expiredGrandFibonaccenning == false) {
return rewardPerBlockPriorFibonaccening - goldenRatio; //reduce reward by golden ratio(subtract)
} else {
return rewardPerBlockPriorFibonaccening * ((100 * EVMnumberFormat - goldenRatio)/100 * EVMnumberFormat); //reduce by a goldenth ratio of a percenth (multiply by) ....
}
}
//gets total(circulating) supply for XVMC token(deducting from dead address and thhis smart contract that holds penalties)
function getTotalSupply() {
return IERC20(ourERCtokenAddress).totalSupply() - ERC20(ourERCtokenAddress).balanceOf(this) - ERC20(ourERCtokenAddress).balanceOf(deadAddress);
}
//TO-DO PREVENT CALLING OF MOST FUNCTIONS WHEN GRAND FIBONNACENING IS ACTIVE!!! (freeze funciton..perhaps should be during several things)
function InitiateSetMinDeposit(int depositingTokens, int number) {
if(number < minimum) { reject "immutable minimum 1000tokens" }
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if (number < costToVote) {
if (depositingTokens != costToVote) { reject "costs to vote" }
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposalMinDeposit.push("true", block.timestamp, depositingTokens, number); //submit new proposal
} else {
if (depositingTokens != number) { reject "must deposit as many tokens as new minimum will be" }
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposalMinDeposit.push("true", block.timestamp, 0, number); //submit new proposal
}
}
//reject if proposal is invalid(false), and if the required delay since last call and first call have not been met
function executeSetMinDeposit(int proposalID) {
if(proposalMinDeposit[proposalID][0] == false || proposalMinDeposit[proposalID][1] < (block.timestamp + delayBeforeEnforce) || proposalMinDeposit[proposalID][2] < (block.timestamp + delayBeforeLastCall)) { reject }
costToVote = proposalMinDeposit[proposalID][3]; //update the costToVote according to proposed value
proposalMinDeposit[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too)
}
function vetoSetMinDeposit(int proposalID, int depositingTokens) {
if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != proposalMinDeposit[proposalID][2]) { reject "must match amount to veto"; }
proposalMinDeposit[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
function getCurrentInflation() {
return get value From Another Contract("XVMCPerBlock", contractAddress) // get value for reward per block from masterchef contract
}
//this can only be called by this smart contract(the rebalancePools function)
function updatePool(int poolID, int allocation, bool massUpdate) {
//call the set contract in masterchef
if(poolID != in_array(1,2,3,4,5)) { reject "only can update pre-set poolIDs" } //can only modify pools with certain ID
//if only contract can call then it doesn't really matter, can call them all
{outsidecontractCall-Masterchef} set(poolID, allocation, 0, massUpdate); //set parameters - call function set in Masterchef
}
//can be called anybody, calls maddupdatepools funciton in masterchef
function massUpdatePools() {
{outsidecontractCall-Masterchef} massUpdatePools(); //call massUpdatePools in masterchef
}
//autocompounding pool addresses...
address public pool1 = "0x...";
address public pool2 = "";
address public pool3 = "";
address public pool4 = "";
address public pool5 = "";
address public pool6 = "";
//called by this smart contract only
function calculateShare(int total, int poolshare, int multiplier) {
return ((total /poolshare) * multiplier); //calculate
}
//can be called by anybody, basically re-calculate all the amounts in pools and update pool shares into masterchef
function rebalancePools() {
//get balance for each pool
int balancePool1 = IERC20(pool1).totalSupply();
int balancePool2 = IERC20(pool2).totalSupply();
int balancePool3 = IERC20(pool3).totalSupply();
int balancePool4 = IERC20(pool4).totalSupply();
int balancePool5 = IERC20(pool5).totalSupply();
int balancePool6 = IERC20(pool6).totalSupply();
int total = balancePool1 + balancePool2 + balancePool3 + balancePool4 + balancePool5 + balancePool6;
//have to change first value(replace 0 with pool ID)...find pool ids in masterchef once you deploy autocompounding pools
//call update function that calls the masterchef and updates values
updatePool(0, calculateShare(total, balancePool1, 10), 0);
updatePool(0, calculateShare(total, balancePool2, 30), 0);
updatePool(0, calculateShare(total, balancePool3, 45), 0);
updatePool(0, calculateShare(total, balancePool4, 100), 0);
updatePool(0, calculateShare(total, balancePool5, 115), 0);
updatePool(0, calculateShare(total, balancePool6, 130), 1); //mass update pools on the last one? i think
}
//can only be called by the contract itself IMPORTANT.. only functions of hte smart contract can call this!!
function setInflation(int rewardPerBlock) {
{outsidecontractCall-Masterchef} updateEmissionRate(rewardPerBlock);
//do we need to remember previous reward? IDK!
//add here if needed (not needed??)
rewardPerBlockPriorFibonaccening = rewardPerBlock; //remember new reward as current ?? IDK
}
//call proposal for minimum amount collected for fibonacenning event
//can be called by anbody
function proposeSetMinThresholdFibonaccenning(int depositingTokens, int newMinimum) {
if(newMinimum < minThresholdFibonaccening) { rejecc "cant go lower than 0.1"}
if(depositingTokens < costToVote) { reject "minimum threshold to vote not met";}
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
proposalThresholdFibonnacening.push("true", block.timestamp, newMinimum); //submit new proposal
}
function vetoSetMinThresholdFibonaccenning(int proposalID, int depositingTokens) {
if (proposalThresholdFibonnacening[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != costToVote) { reject "it costs to vote"; }
proposalThresholdFibonnacening[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//enforce function
function executeSetMinThresholdFibonaccenning(int proposalID) {
if(proposalThresholdFibonnacening[proposalID][0] == false || proposalThresholdFibonnacening[proposalID][1] < (block.timestamp + delayBeforeEnforce)) { reject }
thresholdFibonnacening = proposalThresholdFibonnacening[proposalID][2]; //update the threshold to the proposed value
proposalThresholdFibonnacening[proposalID][0] = false; //expire the proposal - prevent it from being called again
}
//should this be vettoable? IDK
//do we even need this... i don't think so because it is included in the fibonacci proposal itself..i think this function below is useless
function setDelay (int depositing tokens, int delay) {
if(delay > maxDelay || delay < minDelay) { reject "not allowed" }
if(depositingTokens != costToVote) { reject "it costs to vote"; }
currentDelay = delay; //make sure as not to confuse days, hours, blocks,... idk how
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//basically this is a "compensation" for re-distributing the penalties
//period of boosted inflation, and after it ends, global inflation reduces
function proposeFibonaccenning(int depositingTokens, int multiplier, int delay, int duration) {
if(depositingTokens != costToVote || ) { reject "costs to submit decisions" }
if(ERC20(putiheretokenaddress).balanceOf(this) < thresholdFibonnacening) { reject "need to collect penalties before calling"; }
if(delay != currentDelay) { reject "respect current delay setting" }
if(eventFibonacceningActive == true) { reject "fibonaccening already activated" }
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
//after it's approved, changing some things should be PAUSED..add this
//this has to be vettoable for sure
//propose new fibonaccening event
fibonaccenningProposal.push(true, block.timestamp, depositingTokens, multiplier, delay, duration)
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
//need to add safeguard so that multiplier*duration does not exceed XXX of amount or something
//must also be able to prevent multiple fibonaccis to be done... perhaps can't submit new proposal IF last one is true
//this might be a global problem though(need to do this on all functions..prevent proposals if one is active already??)
//safeguard is that you need to burn the tokens to execute fibonaccening
}
function vetoFibonaccenning(int proposalID, int depositingTokens) {
if(depositingTokens != costToVote) { reject "costs to vote" }
if(fibonaccenningProposal[proposalID][0] == false) { reject "proposal already vettod" }
fibonaccenningProposal[proposalID][0] = false; //negates proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//there is fibonacenning PRIOR to grandFibonacenningEvent and after it
//the only difference is prior it reduces inflation(subtracts) and afterwards it multiplies by ((100-1.618)/100)
//this is included in the function to setInflation already??
function leverPullFibonaccenningLFG(proposalID) {
//not sure if this is neccessary since the lever should never be pulled if this condition not met
if(ERC20(putiheretokenaddress).balanceOf(this) < thresholdFibonnacening) { reject "need to collect penalties before calling"; }
if(fibonaccenningProposal[proposalID][0] == false { reject "proposal has been rejected"; }
if(block.timestamp < fibonaccenningProposal[proposalID][1] + delayBeforeEnforce) { reject "delay must expire before proposal valid"; }
if( eventFibonacceningActive = true ) { reject "already active" }
{outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(currentInflation * fibonaccenningProposal[proposalID][3]);
//WAITWAIT: HOW TO PREVENT MULTIPLE CALLS FOR LEVER PULLZ? IDK
//what happens if there are multiple pulls?
fibonacenningActiveID = proposalID;
fibonacenningActivatedTimestamp = block.timestamp;
eventFibonacceningActive = true;
transfer(thresholdFibonnacening, deadAddress); //send the coins from .this wallet to deadaddress(burn them to perform fibonaccening)
}
//ends inflation boost, reduces inflation
//anyone can call
function endFibonaccening() {
if(eventFibonacceningActive == false) { reject "fibonaccenning not activated" }
if(block.timestamp < fibonacenningActivatedTimestamp + fibonaccenningProposal[fibonacenningActiveID][5]) { reject "not yet expired"
int newamount = calculateFibonaccenningNewRewardPerBlock();
//set new inflation with fibonacci reduction
{outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(newamount);
eventFibonacceningActive = false;
//does solidity go line by line when executing? Will first line get executed first? If not, then this could be a problem
//update current inflation in global setting to that amount
rewardPerBlockPriorFibonaccening = newamount;
}
struct proposeGrandFibonacenning{
bool valid;
int eventDate;
int proposalTimestamp;
int amountSacrificedForVote;
}
proposeGrandFibonacenning[] public grandFibonacceningProposals;
function initiateProposeGrandFibonacenning(int depositingTokens, int delayFromNow) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
if(eligibleGrandFibonacenning ) // WHEN ARE WE ELIGIBLE FOR THIS EVENT?? hmh need to set still
if(delayFromNow < 3days) { reject }
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
grandFibonacceningProposals.push("true", block.timestamp + delayFromNow, block.timestamp, depositingTokens); //submit new proposal
}
function vetoProposeGrandFibonacenning(int proposalID, int depositingTokens) {
if (grandFibonacceningProposals[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != grandFibonacceningProposals[proposalID][3]) { reject "must match amount to veto"; }
grandFibonacceningProposals[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//the grand fibonnacenning where massive supply is printed in a period of X days
//the duration should be preset to last for 10days roughly
//27 events: 1 hour of boosted rewards where supply goes x1.618 every 12hours or so
bool grandFibonacenningActivated = false;
function theGrandFibonacenningEnforce(proposalID) {
//prepare blockcounters in advance, it will be important
if(expiredGrandFibonaccening) { "already called gtfo"; }
if(!grandFibonacceningProposals[proposalID][0] || grandFibonacceningProposals[proposalID][1] + grandFibonacceningProposals[proposalID][2] < block.timestamp) //not valid
//need to add another function if it has already happened and has been called too
//after event expires set the inflation reduction to become another function!!
grandFibonacenningActivated = true;
//if you multiply by golden ratio whole supply roughly 27times you will get a 1,000,000X coins
//it will look better(higher upside potential), there will be no ceiling(resistances)
//you will be earning more tokens, they will be cheaper,...
//inflation will be lower
int newInflationRate = getTotalSupply() * goldenRatio;
rewardPerBlockPriorFibonaccening = newInflationRate;
/*
MISSING HERE, and grandfibonacenningRunning function.. (need to set somehow for the function to work basically)
*/
}
//function that is executing rewards for grand fibonacenning
int eventCounter = 0;
int lastEventTimestamp;
function grandFibonacenningRunning() {
if(!grandFibonacenningActivated) { reject }
if(getTotalSupply() > 1quadrillion) { grandFibonacenningRunning = false } // expire it somehow and make sure it can't be called no more
//print around 9:00UTC and then do it again around 17:00 UTC every day
//aka make function callable at that time
//also need ot make sure it can't be called again if running
//should we include the tokens in this contract(penalties) or no?
int amountToPrint = getTotalSupply() * 0.6183; // we multiply supply x1.6183(golden raito)
int newRewardPerBlock = amountToPrint / (3600/blocksPerSecond);
{outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(newRewardPerBlock);
eventCounter++;
}
function gracePeriodTransferOwner() priv admin only {
//reject call after October 15
if(block.timestamp > xxx) { reject "Contract is immutable. Grace period only available in the first month for potentital improvements") }
if(gracePeriodActivation == true) { reject "already activated" }
gracePeriodActivation = true;
timestampGracePeriod = block.timestamp;
}
//works as a time-lock. Transfer owner is called and can only be fulfilled after
function afterDelayOwnership(addres newOwnerAddress) priv admin only{
if(gracePeriodActivation == false) { reject "grace period not request"; }
if(timestampGracePeriod + 9999 < block.timestamp) { rejecc "minimum 10k blocks before initiation"; } // effectively roughly 6hour timelock i think
//checks passed, safe to change ownerships
{outsidecontractCall-Masterchef} transferOwnership(newOwnerAddress); //call masterchef function to transfer ownership
}
//do we need this. i mean does it really matter if there is no function for owner? IDK
//CAN BE CALLED BY ANYBODY, basically make it immutable/controlled by nobody
function renounceOwnership() public anybody(idksyntax) {
if(block.timestamp < 15october) { "grace period expires after 30september" }
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
|
shit doesn't really matter cuz after big fibonnaci daz we go down to 25-golden ratio, so need not to remember until then
|
function rapidAdoptionBoost() public {
rapidAdoptionBoost = true;
if(rapidAdoptionBoost) { reject "already been activated"; }
if(block.timestamp < 22.september) { reject "rapidAdoptionBoost can only be activated after this period" }
}
| 1,047,209 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.