file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./partial_match/1/0x8Fbc2bD0F023c282EB6913444f26Ec8EC73DE967/sources/src/utils/YieldMath.sol
|
Splitting sharesInForFYTokenOut in two functions to avoid stack depth limits normalizedSharesReserves = μ sharesReserves za = c/μ (normalizedSharesReserves a) The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) (2^63)^(1 - y/z) ya = fyTokenReserves a The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) (2^63)^(1 - y/z) yxa = (fyTokenReserves - x) aß The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) (2^63)^(1 - y/z) subtotal is calculated as a positive fraction multiplied by a uint so it cannot underflow when casting to uint and its ok to use a raw casting
|
function _sharesInForFYTokenOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenOut,
uint128 a,
int128 c,
int128 mu
) private pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δy (fyTokenOut)
1/μ * ( subtotal )^( invA ) - z
1/μ * (( Za ) + ( Ya ) - ( Yxa )) / (c/μ) )^( invA ) - z
Δz = 1/μ * (( c/μ * μz^(1-t) + y^(1-t) - (y - x)^(1-t)) / (c/μ) )^(1 / (1 - t)) - z
*/
unchecked {
require(
mu.mulu(sharesReserves) <= MAX,
'YieldMath: Rate overflow (nsr)'
);
uint256 za = c.div(mu).mulu(
uint128(mu.mulu(sharesReserves)).pow(a, ONE)
);
require(za <= MAX, 'YieldMath: Rate overflow (za)');
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 yxa = (fyTokenReserves - fyTokenOut).pow(a, ONE);
require(
fyTokenOut <= fyTokenReserves,
'YieldMath: Underflow (yxa)'
);
uint256 zaYaYxa;
require(
(zaYaYxa = (za + ya - yxa)) <= MAX,
'YieldMath: Rate overflow (zyy)'
);
int128 subtotal = int128(ONE).div(mu).mul(
(
uint128(zaYaYxa.divu(uint128(c.div(mu)))).pow(
uint128(ONE),
uint128(a)
)
).i128()
);
uint128 sharesOut = uint128(subtotal) - sharesReserves;
require(
sharesOut <= uint128(subtotal),
'YieldMath: Underflow error'
);
return sharesOut;
}
}
| 4,162,906 |
./partial_match/1/0x39DC6a99209B5e6B81dC8540C86Ff10981ebDA29/sources/BatchDeposit.sol
|
Submit index-matching arrays that form Phase 0 DepositData objects. Will create a deposit transaction per index of the arrays submitted. pubkeys - An array of BLS12-381 public keys. withdrawal_credentials - An array of public keys for withdrawals. signatures - An array of BLS12-381 signatures. deposit_data_roots - An array of the SHA-256 hash of the SSZ-encoded DepositData object. Loop through DepositData arrays submitting deposits Emit `LogSendDepositLeftover` log This function doesn't guard against re-entrancy, and we're calling an untrusted address, but in this situation there is no state, etc. to take advantage of, so re-entrancy guard is unneccesary gas cost. This function uses call.value(), and handles return values/failures by reverting the transaction.
|
function batchDeposit(
bytes[] calldata pubkeys,
bytes[] calldata withdrawal_credentials,
bytes[] calldata signatures,
bytes32[] calldata deposit_data_roots
) external payable {
require(
pubkeys.length == withdrawal_credentials.length &&
pubkeys.length == signatures.length &&
pubkeys.length == deposit_data_roots.length,
"#BatchDeposit batchDeposit(): All parameter array's must have the same length."
);
require(
pubkeys.length > 0,
"#BatchDeposit batchDeposit(): All parameter array's must have a length greater than zero."
);
require(
msg.value >= DEPOSIT_AMOUNT.mul(pubkeys.length),
"#BatchDeposit batchDeposit(): Ether deposited needs to be at least: 32 * (parameter `pubkeys[]` length)."
);
uint256 deposited = 0;
for (uint256 i = 0; i < pubkeys.length; i++) {
DEPOSIT_CONTRACT.deposit.value(DEPOSIT_AMOUNT)(
pubkeys[i],
withdrawal_credentials[i],
signatures[i],
deposit_data_roots[i]
);
deposited = deposited.add(DEPOSIT_AMOUNT);
}
assert(deposited == DEPOSIT_AMOUNT.mul(pubkeys.length));
uint256 ethToReturn = msg.value.sub(deposited);
if (ethToReturn > 0) {
emit LogSendDepositLeftover(msg.sender, ethToReturn);
(msg.sender).sendValue(ethToReturn);
}
}
| 4,041,777 |
// SPDX-License-Identifier: None
// All rights reserved. @2022
/*
__ ___ _ _ _____ _ _
\ \ / / | (_) | / ____| | | | |
\ \ /\ / /| |__ _| |_ ___| | _ _| |__ ___| | ___ ___ ___
\ \/ \/ / | '_ \| | __/ _ \ | | | | | '_ \ / _ \ |/ _ \/ __/ __|
\ /\ / | | | | | || __/ |___| |_| | |_) | __/ | __/\__ \__ \
\/ \/ |_| |_|_|\__\___|\_____\__,_|_.__/ \___|_|\___||___/___/
*/
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
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) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/interfaces/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/interfaces/IERC2981.sol
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (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/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (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);
/**
* @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/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (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/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// 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/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (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/Cubeless.sol
pragma solidity ^0.8.7;
abstract contract ERC2981Collection is IERC2981 {
// ERC165
// _setRoyalties(address,uint256) => 0x40a04a5a
// royaltyInfo(uint256,uint256) => 0x2a55205a
// ERC2981Collection => 0x6af56a00
address private royaltyAddress;
uint256 private royaltyPercent;
// Set to be internal function _setRoyalties
// _setRoyalties(address,uint256) => 0x40a04a5a
function _setRoyalties(address _receiver, uint256 _percentage) internal {
royaltyAddress = _receiver;
royaltyPercent = _percentage;
}
// Override for royaltyInfo(uint256, uint256)
// royaltyInfo(uint256,uint256) => 0x2a55205a
/*
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view override(IERC2981) virtual returns (
address receiver,
uint256 royaltyAmount
) {
receiver = royaltyAddress;
// This sets percentages by price * percentage / 100
royaltyAmount = _salePrice * royaltyPercent / 100;
}
*/
}
/// owner: 𝗪𝗛𝗜𝗧𝗘𝗖𝗨𝗕𝗘𝗟𝗘𝗦𝗦 - 𝗦𝗬𝗗𝗡𝗘𝗬 - 𝗔𝗨𝗦𝗧𝗥𝗔𝗟𝗜𝗔
/// author: pamuk.eth
/// White Cubeless Pty Ltd is a blockchain technology company registered in Australia. All rights reserved by White Cubeless Pty Ltd. @2022
/// Live Version -
/**
* @dev Heavily customized ERC721 supporting,
*
* - Multiple drop management
* - Contingent transactions
* - Reservation
* - Owner mint
* - URI recycling
* - Merkletree Presale
* - Drop-Wise Royalties
* - PublicSale
* - 3 Way Balance of Powers
*/
contract WhiteCubeless is ERC721Enumerable,ERC2981Collection {
//𝗩𝗔𝗥𝗜𝗔𝗕𝗟𝗘 𝗗𝗘𝗖𝗟𝗔𝗥𝗔𝗧𝗜𝗢𝗡𝗦:
//𝗘𝗩𝗘𝗡𝗧𝗦
/// @dev emitted after mint
event Mint(address indexed _to, uint256 indexed _tokenId, uint256 indexed _artworkId);
/// @dev emitted after burn
event Burn( uint256 indexed _tokenId, uint256 indexed _artworkId);
/// @dev freezes metadata for marketplaces
event PermanentURI( string _value, uint256 indexed _id);
/// @dev emitted after artwork adeed
event ArtworkAdded( string uri, uint256 _ArtworkId,uint256 _Limit);
//𝗚𝗟𝗢𝗕𝗔𝗟
uint256 constant public ONE_MILLION = 1_000_000;
//𝗩𝗘𝗥𝗦𝗜𝗢𝗡𝗜𝗡𝗚
/// @dev this is to make sure any tokenID generated by WhiteCubeless is unique even the contract is different.
uint256 constant public WhiteCubelessGalleryVersion = 1;
/// @dev assign first ID
uint256 public nextartworkId = WhiteCubelessGalleryVersion*ONE_MILLION;
//𝗚𝗔𝗟𝗟𝗘𝗥𝗬 𝗘𝗗𝗜𝗧𝗜𝗢𝗡𝗦
/// @dev drop struct
struct Artwork {
string artworkBaseIpfsURI; // 'ipfs://CID/'
address royaltyReceiver; // default assigned in init
uint256 minted; // already minted + reserved
uint256 count; // minted + reserved + burned
uint256 artworkLimit; // max limit
uint256 royaltiesInBP; // default assigned in init
uint256 artworkPrice; // init assignment, can change later
uint256 reserved; // count of reserved
bool locked; // once locked nobody can change royalty, URI and other ctirical info, locking is irreversible
bool paused; // pause for minting
bool presale; // init assignment
uint256[] available_list; // generated in init for URI recycling [1,2,3] - [0,2,3]
}
mapping(uint256 => Artwork) internal artworks;
mapping(uint256 => bool) internal artworkCheck;
mapping(uint256 => uint256) internal tokenIdToArtworkId;
mapping(uint256 => uint256) internal tokenIdToIpfsHash;
mapping(uint256 => uint256[]) internal artworkIdToTokenIds;
mapping (bytes32 => uint256) internal whiteListLimits;
mapping (uint256 => bool) public paidWithCard;
mapping (uint256 => uint256) public paidDate;
mapping (uint256 => bool) public burnDisabled;
mapping (uint256 => bool) public isBurned;
//𝗣𝗥𝗜𝗩𝗜𝗟𝗘𝗚𝗘𝗦
mapping(address => bool) public isOperator;
mapping(address => bool) public isGalleryReserver;
address public admin;
address public gateKeeperOne;
address public gateKeeperTwo;
address public defaultRoyaltyReceiver;
bytes32 public root;
bool public gateKeeperOneAllowMinting=false;
bool public gateKeeperTwoAllowMinting=false;
bool public gateKeeperOneAppointed=false;
bool public gateKeeperTwoAppointed=false;
bool public gateKeeperOneChangeAdmin=false;
bool public gateKeeperTwoChangeAdmin=false;
//𝗥𝗢𝗬𝗔𝗟𝗧𝗜𝗘𝗦
uint256 public defaultRoyaltiesInBP = 800; // 8%
uint256 public MINT_HARD_LIMIT=10; // cannot mint more than 10
uint256 public WHITELIST_PER_ACCOUNT_LIMIT=5; // each whitelisted account can get 5 pieces before the whitelist reset
uint256 public currentMappingVersion; // resettable mapping
uint256 public DAY_LIMIT=90; // cannot burn a credit card sale after this limit
//𝗠𝗢𝗗𝗜𝗙𝗜𝗘𝗥𝗦
/// @dev checks if the tokenId exists
modifier onlyValidTokenId(uint256 _tokenId)
{
require(_exists(_tokenId));
_;
}
/// @dev checks if transaction is direct or from a contract
modifier onlyAccounts () {
require(msg.sender == tx.origin);
_;
}
/// @dev checks the lock status of the artwork
modifier onlyUnlocked(uint256 _artworkId)
{
require(!artworks[_artworkId].locked);
_;
}
/// @dev checks if the minting is paused or not
modifier onlyUnPaused(uint256 _artworkId)
{
require(!artworks[_artworkId].paused);
_;
}
/// @dev only called by admin
modifier onlyAdmin()
{
require(msg.sender == admin);
_;
}
/// @dev only called by admin and operator
modifier onlyOperator()
{
require(isOperator[msg.sender] || msg.sender==admin );
_;
}
/// @dev only called by admin and operator and reserver
modifier onlyGalleryReserver()
{
// checks if the msg sender is reserver or not
require((isGalleryReserver[msg.sender]) || (isOperator[msg.sender]) || (msg.sender==admin));
_;
}
/// @dev only called by GateKeeperOne
modifier onlyGateKeeperOne()
{
require(gateKeeperOneAppointed);
require(msg.sender == gateKeeperOne);
_;
}
/// @dev only called by GateKeeperTwo
modifier onlyGateKeeperTwo()
{
require(gateKeeperTwoAppointed);
require(msg.sender == gateKeeperTwo);
_;
}
/// @dev only called by GateKeeperTwo and GateKeeperOne, makes sure they are appointed as well.
modifier onlyGateKeeper()
{
// checks if the msg sender is gatekeeper or not
require((msg.sender == gateKeeperOne) || (msg.sender == gateKeeperTwo));
require(gateKeeperTwoAppointed);
require(gateKeeperOneAppointed);
_;
}
constructor(string memory _tokenName, string memory _tokenSymbol, bytes32 merkleroot) ERC721(_tokenName, _tokenSymbol)
{
admin = msg.sender;
root = merkleroot;
//gatekeepers are admin in the initial deployment
gateKeeperOne=msg.sender;
gateKeeperTwo=msg.sender;
//minting is toggled to true
gateKeeperOneAllowMinting=true;
gateKeeperTwoAllowMinting=true;
//gatekeepers can change admin if they have unanymous decision
gateKeeperOneChangeAdmin=false;
gateKeeperTwoChangeAdmin=false;
defaultRoyaltyReceiver=msg.sender;
//𝗔𝗙𝗧𝗘𝗥 𝗗𝗘𝗣𝗟𝗢𝗬 𝗧𝗢𝗗𝗢:
// 1- Appoint GateKeeper - Keep in Mind Admin Can Only Appoint a GateKeeper Once
}
// 𝗔𝗗𝗠𝗜𝗡 𝗣𝗥𝗜𝗩𝗜𝗟𝗔𝗚𝗘𝗦
/// @dev change admin to a new account
function changeAdmin(address _address) onlyAdmin public
{
admin = _address;
}
/// @dev adds Operator which can carry daily hot wallet duties - admin only
function addOperator(address _address) onlyAdmin public
{
isOperator[_address] = true;
}
/// @dev remove privilages - Admin only
function removeOperator(address _address) onlyAdmin public
{
isOperator[_address] = false;
}
/// @dev add Gallery Reserver can only reserve artwork - Operator
function addGalleryReserver(address _address) onlyOperator public
{
isGalleryReserver[_address] = true;
}
/// @dev remove privilages - Operator
function removeGalleryReserver(address _address) onlyOperator public
{
isGalleryReserver[_address] = false;
}
/// @dev GAtekeepers can stop minting, minting is on by default, has to be appointed before first minting
function appointGateKeeperOne(address _address) onlyAdmin public
{
require (gateKeeperOneAppointed== false);
gateKeeperOne= _address;
gateKeeperOneAppointed=true;
}
/// @dev GAtekeepers can stop minting, minting is on by default, has to be appointed before first minting
function appointGateKeeperTwo(address _address) onlyAdmin public
{
require (gateKeeperTwoAppointed== false);
gateKeeperTwo= _address;
gateKeeperTwoAppointed=true;
}
/// @dev Admin can withdraw ETH to admin account
function withdrawAll() public onlyAdmin
{
uint256 balance = address(this).balance;
require(balance > 0);
_withdraw(admin, balance);
}
/// @dev withdraw function
function _withdraw(address _address, uint256 _amount) private
{
(bool success, ) = _address.call{value: _amount}("");
require(success);
}
//𝗚𝗔𝗧𝗘𝗞𝗘𝗘𝗣𝗘𝗥 𝗣𝗥𝗜𝗩𝗜𝗟𝗘𝗚𝗘𝗦
/// @dev Start/Stop Minting, On by default
function gateKeeperOneToggleMinting(bool toggle_bool) onlyGateKeeperOne public
{
gateKeeperOneAllowMinting= toggle_bool;
}
/// @dev Start/Stop Minting, On by default
function gateKeeperTwoToggleMinting(bool toggle_bool) onlyGateKeeperTwo public
{
gateKeeperTwoAllowMinting= toggle_bool;
}
/// @dev only Gatekeeper can change itself
function gateKeeperOneChangeAddress(address _address) onlyGateKeeperOne public
{
gateKeeperOne= _address;
}
/// @dev only Gatekeeper can change itself
function gateKeeperTwoChangeAddress(address _address) onlyGateKeeperTwo public
{
gateKeeperTwo= _address;
}
/// @dev initiate admin recovery, true to vote to change admin
function gateKeeperOneToggleAdminChange(bool toggle_bool) onlyGateKeeperOne public
{
gateKeeperOneChangeAdmin= toggle_bool;
}
/// @dev initiate admin recovery, true to vote to change admin
function gateKeeperTwoToggleAdminChange(bool toggle_bool) onlyGateKeeperTwo public
{
gateKeeperTwoChangeAdmin= toggle_bool;
}
/// @dev if both admin change votes are true, this funtion assigns a new admin
function gateKeeperAdminOverride(address _address) onlyGateKeeper public
{
//gatekeepers can change admin if they agree to do so
require(gateKeeperTwoChangeAdmin,"1");
require(gateKeeperOneChangeAdmin,"2");
gateKeeperTwoChangeAdmin=false;
gateKeeperOneChangeAdmin=false;
admin = _address;
}
//𝗢𝗣𝗘𝗥𝗔𝗧𝗜𝗢𝗡𝗔𝗟 𝗪𝗛𝗜𝗧𝗘𝗟𝗜𝗦𝗧𝗘𝗗 𝗙𝗨𝗡𝗖𝗧𝗜𝗢𝗡𝗦
/// @dev change multiple mint per artwork
function updateMintHardLimit(uint256 _hardlimit) onlyOperator public
{
MINT_HARD_LIMIT = _hardlimit;
}
/// @dev freeze metadata of the multiple tokens if neccesary, contact [email protected] if you need Frozen badge in marketplaces
function freezeMetadataList(uint256[] memory _tokenIds) onlyOperator public
{
require (_tokenIds.length < 20, "1");
for (uint i; i<_tokenIds.length;)
{
uint256 tokenId=_tokenIds[i];
require(_exists(tokenId), "2");
emit PermanentURI(tokenURI(tokenId),tokenId);
unchecked { ++i ;}
}
}
/// @dev changes the royalty receiver, only applicable for new artworks
function changeDefaultRoyaltyReceiver(address _address) onlyOperator public
{
defaultRoyaltyReceiver = _address;
}
/// @dev merkleroot for presales, only one root at a time
function setMerkleRoot(bytes32 merkleroot) onlyOperator public
{
root = merkleroot;
}
/// @dev max tokens a whitelisted account can mint
function setWhitelistPerAccount(uint256 maximum_per_account) onlyOperator public
{
WHITELIST_PER_ACCOUNT_LIMIT = maximum_per_account;
}
/// @dev after day_limit, contract can't burn transferred tokens
function setCCDayLimit(uint256 day_limit) onlyOperator public
{
require(day_limit<=90);
DAY_LIMIT = day_limit;
}
/// @dev multiple disables remote burning for tokens, immediately, triggered manually when payment is cleared
function disableMultipleCreditCardBurn(uint256[] memory _tokenIds, uint256 check_len) onlyOperator public
{
uint256 q1=_tokenIds.length;
require(q1==check_len);
for (uint i; i < check_len;)
{
disableCreditCardBurn(_tokenIds[i]);
unchecked { ++i ;}
}
}
/// @dev disables remote burning for tokens, immediately, triggered when payment is cleared, contact [email protected] to secure your token if purchased via traditional methods
function disableCreditCardBurn(uint _tokenId) onlyOperator public
{
burnDisabled[_tokenId]=true;
}
/// @dev add multiple artworks
function addMultipleArtwork(uint256[] memory _artworkLimits,uint256[] memory _prices,string[] calldata _artworkBaseIpfsURIs,bool[] memory _presales,uint256 len_check) onlyOperator public
{
uint256 q2=_artworkLimits.length;
uint256 q3=_prices.length;
uint256 q4=_artworkBaseIpfsURIs.length;
uint256 q5=_presales.length;
require(q2==len_check,"2");
require(q3==len_check,"3");
require(q4==len_check,"4");
require(q5==len_check,"5");
for (uint i; i < len_check;)
{
addArtwork( _artworkLimits[i],_prices[i], _artworkBaseIpfsURIs[i],_presales[i]);
unchecked { ++i ;}
}
}
/// @dev add artwork , once added cannot be undone
function addArtwork(uint256 _artworkLimit,uint256 _price, string calldata _artworkBaseIpfsURI,bool presale) onlyOperator public
{
uint256 artworkId = nextartworkId;
require(artworkCheck[artworkId]==false,"1");
artworks[artworkId].artworkLimit = _artworkLimit;
artworks[artworkId].artworkPrice=_price;
artworkCheck[artworkId]=true;
//
artworks[artworkId].royaltyReceiver=defaultRoyaltyReceiver;
artworks[artworkId].royaltiesInBP=defaultRoyaltiesInBP;
artworks[artworkId].presale=presale;
artworks[artworkId].minted=0;
artworks[artworkId].locked=false;
artworks[artworkId].artworkBaseIpfsURI = _artworkBaseIpfsURI;
artworks[artworkId].available_list=new uint[](_artworkLimit);
for (uint i; i < _artworkLimit;)
{
artworks[artworkId].available_list[i]=i+1;
unchecked { ++i ;}
}
emit ArtworkAdded( _artworkBaseIpfsURI, artworkId,_artworkLimit);
nextartworkId = nextartworkId+1;
}
/// @dev locks an artwork for editing, manually triggered after edition is sold out
function updateArtworkLock(uint256 _artworkId,bool lock_bool) onlyOperator onlyUnlocked(_artworkId) public
{
//when locked, nobody can unlock therefore the whole structure is frozen
artworks[_artworkId].locked = lock_bool;
}
/// @dev pauses artwork for minting
function updateArtworkPause(uint256 _artworkId,bool pause_bool) onlyOperator public
{
//when locked, nobody can unlock therefore the whole structure is frozen
artworks[_artworkId].paused = pause_bool;
}
/// @dev multiple IPFS change in case there is a problem with the IPFS supplied in init, cannot be used after locking
function updateMultipleArtworkBaseIpfsURI(uint256[] calldata _artworkIds,string[] calldata _artworkBaseIpfsURIs, uint256 check_len) onlyOperator public
{
uint256 q1=_artworkBaseIpfsURIs.length;
uint256 q2=_artworkIds.length;
require(q1==check_len,"1");
require(q2==check_len,"2");
for (uint i; i < check_len;)
{
updateArtworkBaseIpfsURI(_artworkIds[i], _artworkBaseIpfsURIs[i]);
unchecked { ++i ;}
}
}
/// @dev IPFS change in case there is a problem with the IPFS supplied in init, cannot be used after locking
function updateArtworkBaseIpfsURI(uint256 _artworkId, string calldata _artworkBaseIpfsURI) onlyOperator onlyUnlocked(_artworkId) public
{
artworks[_artworkId].artworkBaseIpfsURI = _artworkBaseIpfsURI;
}
/// @dev multiple price change in case there is a problem with the price supplied in init, cannot be used after locking
function updateMultipleArtworkPrice(uint256[] calldata _artworkIds,uint256[] calldata _prices, uint256 check_len) onlyOperator public
{
uint256 q1=_prices.length;
uint256 q2=_artworkIds.length;
require(q1==check_len,"1");
require(q2==check_len,"2");
for (uint i ; i < check_len; )
{
updateArtworkPrice(_artworkIds[i], _prices[i]);
unchecked { ++i ;}
}
}
/// @dev price change in case there is a problem with the price supplied in init, cannot be used after locking
function updateArtworkPrice(uint256 _artworkId, uint256 _price) onlyOperator onlyUnlocked(_artworkId) public
{
artworks[_artworkId].artworkPrice = _price;
}
/// @dev enable presale for an artwork on the fly
function updateArtworkPresale(uint256 _artworkId, bool _presaleBool) onlyOperator onlyUnlocked(_artworkId) public
{
artworks[_artworkId].presale = _presaleBool;
}
/// @dev multiple change URI extension that comes after ipfs://{CID}/, last resort if there is a sequencing problem after recycling, cannot be done after lock
function overrideMultipleTokenIPFSHash(uint256[] calldata _newHashs , uint256[] calldata _tokenIds, uint256 check_len) onlyOperator public
{
uint256 q1=_newHashs.length;
uint256 q2=_tokenIds.length;
require(q1==check_len,"1");
require(q2==check_len,"2");
for (uint i ; i < check_len; )
{
overrideTokenIPFSHash(_newHashs[i], _tokenIds[i]);
unchecked { ++i ;}
}
}
/// @dev change URI extension that comes after ipfs://{CID}/, last resort if there is a sequencing problem after recycling, cannot be done after lock
function overrideTokenIPFSHash(uint256 _newHash , uint256 _tokenId) onlyOperator public
{
//check if artwork is locked
require(_exists(_tokenId), "1");
require(!artworks[tokenIdToArtworkId[_tokenId]].locked,"2");
tokenIdToIpfsHash[_tokenId]=_newHash;
}
/// @dev change available to mint array if there is a problem in sequencing, this applies for future mints
function overrideAvailableArray(uint256 _artworkId,uint256[] calldata available_array ) onlyOperator onlyUnlocked(_artworkId) public
{
// jus tin case if available array mixes up
require(available_array.length == artworks[_artworkId].available_list.length,"1");
require(artworkCheck[_artworkId],"2");
for (uint i; i < artworks[_artworkId].available_list.length;)
{
artworks[_artworkId].available_list[i]=available_array[i];
unchecked { ++i ;}
}
}
/// @dev royalty percentage change for existing artworks
function changeArtworkRoyaltiesInBP(uint256 _artworkId,uint256 _royaltiesInBP) onlyOperator onlyUnlocked(_artworkId) public
{
artworks[_artworkId].royaltiesInBP = _royaltiesInBP;
}
/// @dev royalty address change for existing artworks
function changeArtworkRoyaltyReceiver(uint256 _artworkId,address _royaltyReceiver) onlyOperator onlyUnlocked(_artworkId) public
{
artworks[_artworkId].royaltyReceiver = _royaltyReceiver;
}
//𝗠𝗜𝗡𝗧𝗜𝗡𝗚
/**
* @dev mints a token for the gallery.
*
* Requirements:
*
* - `artwork` should be Unpaused.
* - only operator can call
*
* Functionality:
* - can mint reserved tokens
* - can mint credit card tokens where gallery can burn in 90 days if the payment is fraudulent
* - can mint tokens for other OTC deals
*/
function galleryMint(address _to, uint256 _artworkId, bool _freeze,uint256 quantity,bool credit_card_sale,bool reserved) onlyOperator onlyUnPaused(_artworkId) external returns (uint256[] memory)
{
// if the sale is done via credit card, we reserve right to burn for 90days
require(artworkCheck[_artworkId],"1");
require(quantity<=MINT_HARD_LIMIT, "3");
require(!artworks[_artworkId].locked , "4");
require(gateKeeperOneAllowMinting , "5");
require(gateKeeperOneAppointed, "6");
require(gateKeeperTwoAllowMinting, "7");
require(gateKeeperTwoAppointed, "8");
if (reserved==false)
{
require(artworks[_artworkId].minted + quantity <= artworks[_artworkId].artworkLimit, "2");
}
if (reserved)
{
//in the mint we will increment minted
// we need to deduct from reserved and minted before hand so that minted will come to the correct quantuty
require(artworks[_artworkId].reserved - quantity >= 0, "9"); //make sure it as actually reserved
require(artworks[_artworkId].minted - quantity >= 0, "10"); //something wrong
}
uint[] memory tokenIds = new uint[](quantity);
for (uint i ; i < quantity; )
{
if (reserved)
{
artworks[_artworkId].reserved=artworks[_artworkId].reserved-1; // unreserve the minted
artworks[_artworkId].minted=artworks[_artworkId].minted-1; // unreserve the minted
}
uint tokenId=_mintToken(_to, _artworkId,_freeze);
tokenIds[i]=tokenId;
paidWithCard[tokenId]=credit_card_sale;
paidDate[tokenId]=block.timestamp;
unchecked { ++i ;}
}
return tokenIds;
}
/// @dev reserves a token for future sale
function galleryReserve( uint256 _artworkId,uint256 quantity) onlyGalleryReserver external
{
// can reserve while paused
require(artworkCheck[_artworkId],"1");
require(artworks[_artworkId].minted+quantity <= artworks[_artworkId].artworkLimit, "2");
require(quantity<=MINT_HARD_LIMIT, "3");
require(!artworks[_artworkId].locked , "4");
require(gateKeeperOneAllowMinting , "5");
require(gateKeeperOneAppointed, "6");
require(gateKeeperTwoAllowMinting, "7");
require(gateKeeperTwoAppointed, "8");
//add the reserved and minted
artworks[_artworkId].minted=artworks[_artworkId].minted+quantity;
artworks[_artworkId].reserved=artworks[_artworkId].reserved+quantity;
}
/// @dev unreserves a token for future sale
function galleryUnReserve( uint256 _artworkId,uint256 quantity) onlyGalleryReserver external
{
// if the sale is done via credit card, we reserve right to burn for 90days
// can reserve while paused
require(artworkCheck[_artworkId],"1");
require(artworks[_artworkId].minted-quantity >= 0, "2");
require(artworks[_artworkId].reserved-quantity >= 0, "3");
require(quantity<=MINT_HARD_LIMIT, "4");
require(!artworks[_artworkId].locked , "5");
require(gateKeeperOneAllowMinting , "6");
require(gateKeeperOneAppointed, "7");
require(gateKeeperTwoAllowMinting, "8");
require(gateKeeperTwoAppointed, "9");
//sub the reserved and minted
artworks[_artworkId].minted=artworks[_artworkId].minted-quantity;
artworks[_artworkId].reserved=artworks[_artworkId].reserved-quantity;
}
/// @dev public mint function where ETH is expected for delivery
function publicSaleMint(uint256 _artworkId, bool _freeze, uint256 quantity) public payable onlyAccounts onlyUnPaused(_artworkId) returns (uint256[] memory)
{
require(artworkCheck[_artworkId],"1");
require(msg.value >= artworks[_artworkId].artworkPrice*quantity, "2");
require(artworks[_artworkId].artworkPrice>0, "3");
require(quantity<=MINT_HARD_LIMIT, "4");
require(artworks[_artworkId].minted+quantity <= artworks[_artworkId].artworkLimit, "5");
require(!artworks[_artworkId].locked , "6");
require(gateKeeperOneAllowMinting, "7");
require(gateKeeperTwoAllowMinting, "8");
require(gateKeeperOneAppointed, "9");
require(gateKeeperTwoAppointed, "10");
require(artworks[_artworkId].presale==false, "11");
uint[] memory tokenIds = new uint[](quantity);
for (uint i; i < quantity;)
{
tokenIds[i]=_mintToken(msg.sender, _artworkId,_freeze);
unchecked { ++i ;}
}
return tokenIds;
}
/// @dev public presale mint function where ETH and whitelisting is expected for delivery
function preSaleMint(uint256 _artworkId, bool _freeze, uint256 quantity, bytes32[] calldata proof) public payable onlyAccounts onlyUnPaused(_artworkId) returns (uint256[] memory)
{
require(artworkCheck[_artworkId],"1");
require(msg.value >= artworks[_artworkId].artworkPrice * quantity, "2");
require(artworks[_artworkId].artworkPrice>0, "3");
require(quantity<=MINT_HARD_LIMIT, "4");
require(artworks[_artworkId].minted+quantity <= artworks[_artworkId].artworkLimit, "5");
require(!artworks[_artworkId].locked , "6");
require(gateKeeperOneAllowMinting, "7");
require(gateKeeperTwoAllowMinting, "8");
require(gateKeeperOneAppointed, "9");
require(gateKeeperTwoAppointed, "10");
require(artworks[_artworkId].presale==true, "11");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(proof, root, leaf),"12");
uint256 limit=getWhiteListedLimit(msg.sender);
uint256 new_limit=limit + quantity;
require(new_limit<=WHITELIST_PER_ACCOUNT_LIMIT,"13");
uint[] memory tokenIds = new uint[](quantity);
_setLimit(msg.sender,new_limit);
for (uint i ; i < quantity;)
{
tokenIds[i]=_mintToken(msg.sender, _artworkId,_freeze);
unchecked { ++i ;}
}
return tokenIds;
}
/// @dev seach for a non 0, unassigned ID and add it as extension, used for recycling the IPFS link
function getNextAvailableExtId(uint256 _artworkId) internal returns (bool found,uint256 ext_id)
{
//loop the avialble
//if it is not 0, break and return
// if 0
ext_id=0;
uint256[] storage avails=artworks[_artworkId].available_list;
found=false;
for (uint i ; i < avails.length;)
{
uint256 val=artworks[_artworkId].available_list[i];
if (val!=0)
{
artworks[_artworkId].available_list[i]=0;
ext_id=val;
found=true;
break;
}
unchecked { ++i ;}
}
return (found,ext_id);
}
/// @dev all mint functions call this function
function _mintToken(address _to, uint256 _artworkId, bool _freeze) internal returns (uint256 _tokenId)
{
artworks[_artworkId].minted = artworks[_artworkId].minted + 1;
artworks[_artworkId].count = artworks[_artworkId].count + 1;
uint256 tokenIdToBe = (_artworkId * ONE_MILLION) + artworks[_artworkId].count;
require(artworks[_artworkId].count<ONE_MILLION,"1");
(bool found_,uint256 ext_id_)=getNextAvailableExtId(_artworkId);
require(found_,"2");
_mint(_to, tokenIdToBe);
tokenIdToArtworkId[tokenIdToBe] = _artworkId;
artworkIdToTokenIds[_artworkId].push(tokenIdToBe);
tokenIdToIpfsHash[tokenIdToBe]=ext_id_;
emit Mint(_to, tokenIdToBe, _artworkId);
if (_freeze)
{
emit PermanentURI(tokenURI(tokenIdToBe),tokenIdToBe);
//freeze it, OpenSea convention
}
return tokenIdToBe;
}
/// @dev string concetanation
function append(string memory a, string memory b) internal pure returns (string memory)
{
return string(abi.encodePacked(a, b));
}
/// @dev overrided URI function where URI based on Artwork is returned
function tokenURI(uint256 _tokenId) public view onlyValidTokenId(_tokenId) override returns (string memory)
{
uint256 ipfsHash= tokenIdToIpfsHash[_tokenId];
return append(artworks[tokenIdToArtworkId[_tokenId]].artworkBaseIpfsURI, Strings.toString(ipfsHash));
}
//BURNING
/// @dev internal burn, deletes URI, reduces supply and sends the token to the 0x0.
/// If the token is sold via CC, can remote burn
// If token is sold via ETH, only burn if Operator holds the token
function burnTokens(uint256[] calldata _tokenIds, uint256 check_len) external onlyOperator
{
require(gateKeeperOneAllowMinting, "1");
require(gateKeeperTwoAllowMinting, "2");
require(gateKeeperOneAppointed, "3");
require(gateKeeperTwoAppointed, "4");
uint256 q1=_tokenIds.length;
require(q1==check_len,"5");
for (uint i ; i < q1;)
{
if (paidWithCard[_tokenIds[i]])
{
_creditCardBurn(_tokenIds[i]);
}
else
{
_burnToken(_tokenIds[i],msg.sender);
}
unchecked { ++i ;}
}
}
/// @dev burn function resets the states
function _burnToken(uint256 _tokenId,address msg_sender) internal
{
require(_exists(_tokenId), "1");
address token_owner = ERC721.ownerOf(_tokenId);
require(msg_sender==token_owner ,"2");
uint256 _artworkId=tokenIdToArtworkId[_tokenId];
require(_artworkId!=0,"3");
//get the hash of the token and equate it to a value other than 0
uint256 ipfsHash=tokenIdToIpfsHash[_tokenId];
artworks[_artworkId].minted = artworks[_artworkId].minted - 1;
tokenIdToArtworkId[_tokenId] = 0;
tokenIdToIpfsHash[_tokenId]=0;
artworks[_artworkId].available_list[ipfsHash-1]=ipfsHash; //burned ID is available for recycling
isBurned[_tokenId]=true;
_burn(_tokenId);
emit Burn(_tokenId,_artworkId);
}
/// @dev burn function that doesn't check ownership
function _creditCardBurn(uint256 _tokenId) internal
{
//function to burn the token if it is bought via credit card
// this functionality is only valid for 90 days after mint and will be used a last resort against fraud
// Please contact us via [email protected] if you to want to disable that earlier, you might be subject to KYC depending on the situation.
//Note that this function is only callable if paidWithCard is true.
// The only scenerio where this can happen is publicGalleryMint
require(_exists(_tokenId), "1");
require(paidWithCard[_tokenId], "2");
require(block.timestamp-paidDate[_tokenId]<=DAY_LIMIT * 86400,"3");
require(burnDisabled[_tokenId]==false,"4");
uint256 ipfsHash=tokenIdToIpfsHash[_tokenId];
uint256 _artworkId=tokenIdToArtworkId[_tokenId];
require(_artworkId!=0,"5");
artworks[_artworkId].minted = artworks[_artworkId].minted-1;
tokenIdToArtworkId[_tokenId] = 0;
tokenIdToIpfsHash[_tokenId]=0;
artworks[_artworkId].available_list[ipfsHash-1]=ipfsHash; //burned ID is available for recycling
isBurned[_tokenId]=true;
_burn(_tokenId);
emit Burn(_tokenId,_artworkId);
}
//𝗥𝗢𝗬𝗔𝗟𝗧𝗜𝗘𝗦
/// @dev EIP-2981 royalty override
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address receiver, uint256 royaltyAmount)
{
address _royaltiesReceiver = artworks[tokenIdToArtworkId[_tokenId]].royaltyReceiver;
uint256 _royaltiesinBPartwork = artworks[tokenIdToArtworkId[_tokenId]].royaltiesInBP;
uint256 _royalties = _salePrice*_royaltiesinBPartwork/10000;
return (_royaltiesReceiver, _royalties);
}
/// @notice Informs callers that this contract supports ERC2981
/// this is for future usage, hope marketplaces can see our royalty declarations
function supportsInterface(bytes4 interfaceId) public view override(ERC721Enumerable,IERC165) returns (bool)
{
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
//𝗩𝗜𝗘𝗪 𝗙𝗨𝗡𝗖𝗧𝗜𝗢𝗡𝗦
/// @dev gives artwork information
function artworkTokenInfo(uint256 _artworkId) view public returns (uint256 minted, uint256 artworkLimit , bool locked,uint256 price,uint256 count,string memory artworkBaseIpfsURI,uint256 reserved)
{
minted = artworks[_artworkId].minted;
//minted includes both reserved and minted
reserved = artworks[_artworkId].reserved;
//to keep track of reserved, only deduct if reserve minted or unreserved
artworkLimit = artworks[_artworkId].artworkLimit;
locked=artworks[_artworkId].locked;
price=artworks[_artworkId].artworkPrice;
count=artworks[_artworkId].count;
artworkBaseIpfsURI = artworks[_artworkId].artworkBaseIpfsURI;
}
/// @dev all tokens, burned ones are shown as 0 in the result
function artworkShowAllTokens(uint256 _artworkId) public view returns (uint256[] memory)
{
uint256[] memory tokens=artworkIdToTokenIds[_artworkId];
uint len=tokens.length;
for (uint i ; i < len;)
{
uint256 val=tokens[i];
if (isBurned[val])
{
tokens[i]=0;
}
unchecked { ++i ;}
}
return tokens;
}
/// @dev tokenId to ArtworkID
function showArtworkOfToken(uint256 _tokenId) public view returns (uint256)
{
return tokenIdToArtworkId[_tokenId];
}
/// @dev artwork to IPFS CID
function showIpfsHash(uint256 _artworkId) public view returns (uint256)
{
return tokenIdToIpfsHash[_artworkId];
}
/// @dev remaining time to remotely burn a credit card token
function showCCSecondsRemaining(uint256 _tokenId) public view returns (uint)
{
return (DAY_LIMIT * 86400)-(block.timestamp-paidDate[_tokenId]);
}
/// @dev returns if user cna reserve a quantity at the moment
function isReservable(uint quantity,uint _artworkId) public view returns (bool)
{
if ((artworks[_artworkId].minted+quantity <= artworks[_artworkId].artworkLimit) && (artworkCheck[_artworkId]))
{
return true;
}
return false;
}
/// @dev available array display
function showAvailableArray(uint256 _artworkId) public view returns (uint256[] memory)
{
return artworks[_artworkId].available_list;
}
//RESETTABLE MAPPING
/**
* @dev A resettable mapping implementation using clever hashing
*
*
*
* Functionality:
*
* - Resets the whitelisted addresses for the next drop.
*
*/
/// @dev how much a whitelisted user minted
function getWhiteListedLimit(address whitelistedAddress) public view returns(uint256)
{
bytes32 key = keccak256(abi.encodePacked(currentMappingVersion, whitelistedAddress));
return whiteListLimits[key];
}
/// @dev set the number of mints a whitelisted user called
function _setLimit(address whitelistedAddress, uint256 newLimit) internal
{
bytes32 key = keccak256(abi.encodePacked(currentMappingVersion, whitelistedAddress));
whiteListLimits[key] = newLimit;
}
/// @dev reset the whitelisted limits
function resetWhiteListedMapping() external onlyOperator
{
currentMappingVersion++;
}
/// @dev a way to delete entries from the mapping,
function recoverGas(uint256 _version, address whitelistedAddress) external onlyOperator
{
require(_version < currentMappingVersion);
bytes32 key = keccak256(abi.encodePacked(_version, whitelistedAddress));
delete(whiteListLimits[key]);
}
}
|
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");
}
| 6,085,816 |
./partial_match/1313161554/0xF36cD4869564a9b0f41845CF06756A14cd31aEf2/sources/ReaperStrategyTrisolaris.sol
|
Function that puts the funds to work. It gets called whenever someone deposits in the strategy's vault contract./
|
function _deposit() internal override {
uint256 wantBalance = IERC20Upgradeable(want).balanceOf(address(this));
if (wantBalance != 0) {
IERC20Upgradeable(want).safeIncreaseAllowance(MASTER_CHEF, wantBalance);
IMasterChefV1(MASTER_CHEF).deposit(poolId, wantBalance);
}
}
| 16,932,996 |
pragma solidity ^0.4.24;
contract RSEvents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
}
contract modularRatScam is RSEvents {}
contract RatScam is modularRatScam {
using SafeMath for *;
using NameFilter for string;
using RSKeysCalc for uint256;
// TODO: check address
RatInterfaceForForwarder constant private RatKingCorp = RatInterfaceForForwarder(0x85de5b2a5c7866044116eade6543f24702d81de1);
RatBookInterface constant private RatBook = RatBookInterface(0xe63d90bbf4d378eeaed5ec5f8266a2e4451ab427);
string constant public name = "RatScam Round #1";
string constant public symbol = "RS1";
uint256 private rndGap_ = 0;
// TODO: check time
uint256 constant private rndInit_ = 24 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => RSdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => RSdatasets.PlayerRounds) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
RSdatasets.Round public round_; // round data
//****************
// TEAM FEE DATA
//****************
uint256 public fees_ = 60; // fee distribution
uint256 public potSplit_ = 45; // pot split distribution
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet");
_;
}
/**
* @dev prevents contracts from interacting with ratscam
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "non smart contract address only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "too little money");
require(_eth <= 100000000000000000000000, "too much money");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
*/
function buyXid(uint256 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// buy core
buyCore(_pID, _affCode, _eventData_);
}
function buyXaddr(address _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core
buyCore(_pID, _affID, _eventData_);
}
function buyXname(bytes32 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core
buyCore(_pID, _affID, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// reload core
reLoadCore(_pID, _affCode, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core
reLoadCore(_pID, _affID, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core
reLoadCore(_pID, _affID, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_.end && round_.ended == false && round_.plyr != 0)
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_.ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit RSEvents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
return ( (round_.keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
if (_now < round_.end)
if (_now > round_.strt + rndGap_)
return( (round_.end).sub(_now) );
else
return( (round_.strt + rndGap_).sub(_now));
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_.end && round_.ended == false && round_.plyr != 0)
{
// if player is winner
if (round_.plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_.pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID)
private
view
returns(uint256)
{
return( ((((round_.mask).add(((((round_.pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round_.keys))).mul(plyrRnds_[_pID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return total keys
* @return time ends
* @return time started
* @return current pot
* @return current player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256)
{
return
(
round_.keys, //0
round_.end, //1
round_.strt, //2
round_.pot, //3
round_.plyr, //4
plyr_[round_.plyr].addr, //5
plyr_[round_.plyr].name, //6
airDropTracker_ + (airDropPot_ * 1000) //7
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
{
// grab time
uint256 _now = now;
// if round is active
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
{
// call core
core(_pID, msg.value, _affID, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_.end && round_.ended == false)
{
// end the round (distributes pot) & start new round
round_.ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit RSEvents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, RSdatasets.EventReturns memory _eventData_)
private
{
// grab time
uint256 _now = now;
// if round is active
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_pID, _eth, _affID, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_.end && round_.ended == false) {
// end the round (distributes pot) & start new round
round_.ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit RSEvents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_.eth < 100000000000000000000 && plyrRnds_[_pID].eth.add(_eth) > 10000000000000000000)
{
uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_.eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys);
// set new leaders
if (round_.plyr != _pID)
round_.plyr = _pID;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 1 prize was won
_eventData_.compressedData += 100000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID].keys = _keys.add(plyrRnds_[_pID].keys);
plyrRnds_[_pID].eth = _eth.add(plyrRnds_[_pID].eth);
// update round
round_.keys = _keys.add(round_.keys);
round_.eth = _eth.add(round_.eth);
// distribute eth
_eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_);
_eventData_ = distributeInternal(_pID, _eth, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID)
private
view
returns(uint256)
{
return((((round_.mask).mul(plyrRnds_[_pID].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID].mask));
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
return ( (round_.eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
return ( (round_.keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(RatBook), "only RatBook can call this function");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(RatBook), "only RatBook can call this function");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of ratscam
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = RatBook.getPlayerID(msg.sender);
bytes32 _name = RatBook.getPlayerName(_pID);
uint256 _laff = RatBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
// grab our winning player and team id's
uint256 _winPID = round_.plyr;
// grab our pot amount
// add airdrop pot into the final pot
uint256 _pot = round_.pot + airDropPot_;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(45)) / 100;
uint256 _com = (_pot / 10);
uint256 _gen = (_pot.mul(potSplit_)) / 100;
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys);
uint256 _dust = _gen.sub((_ppt.mul(round_.keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_com = _com.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
if (!address(RatKingCorp).call.value(_com)(bytes4(keccak256("deposit()"))))
{
_gen = _gen.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_.mask = _ppt.add(round_.mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_.end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.newPot = 0;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID].mask = _earnings.add(plyrRnds_[_pID].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_.end && round_.plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_.end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_.end = _newTime;
else
round_.end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
// uint256 seed = uint256(keccak256(abi.encodePacked(
// (block.timestamp).add
// (block.difficulty).add
// ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
// (block.gaslimit).add
// ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
// (block.number)
// )));
// if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
// return(true);
// else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
returns(RSdatasets.EventReturns)
{
// pay 5% out to community rewards
uint256 _com = _eth * 2 / 100;//5%
// distribute share to affiliate
//uint256 _aff = _eth / 10;//10%
uint256 _aff = 0;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now);
} else {
// no affiliates, add to community
_com += _aff;
}
if (!address(RatKingCorp).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
}
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_)
private
returns(RSdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_)) / 100;//60%
// toss 5% into airdrop pot
//uint256 _air = (_eth / 20);//5%
uint256 _air = 0;//5%
airDropPot_ = airDropPot_.add(_air);
// calculate pot (20%)
uint256 _pot = (_eth.mul(38) / 100);//20%
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_.pot = _pot.add(_dust).add(round_.pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys);
round_.mask = _ppt.add(round_.mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID].mask = (((round_.mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_.keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit RSEvents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only owner can activate
// TODO: set owner
require(
msg.sender == 0x4e0ee71f35cbb738877f31d240a2282d2ac8eb27,
"only owner can activate"
);
// can only be ran once
require(activated_ == false, "ratscam already activated");
// activate the contract
activated_ = true;
round_.strt = now - rndGap_;
round_.end = now + rndInit_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library RSdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library RSKeysCalc {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface RatInterfaceForForwarder {
function deposit() external payable returns(bool);
}
interface RatBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
}
|
============================================================================== _ _ _ _ | _ _ . _ . (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)=====================_|======================================================= logic runs whenever a buy order is executed. determines how to handle incoming eth depending on if we are in an active round or not/ grab time if round is active call core if round is not active check to see if end round needs to be ran end the round (distributes pot) & start new round build event data fire buy and distribute event
|
function buyCore(uint256 _pID, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
{
uint256 _now = now;
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
{
core(_pID, msg.value, _affID, _eventData_);
if (_now > round_.end && round_.ended == false)
{
round_.ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit RSEvents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
}
}
| 11,775,985 |
./full_match/1/0x91BA45E4889127d5e28df074348c6C04974C6Ba2/sources/contracts/Comptroller.sol
|
Checks if the account should be allowed to redeem tokens in the given market cToken The market to verify the redeem against redeemer The account which would redeem the tokens redeemTokens The number of cTokens to exchange for the underlying asset in the market return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/
|
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) override external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
distributeSupplierComp(cToken, redeemer);
return uint(Error.NO_ERROR);
}
| 3,021,501 |
pragma solidity ^0.4.17;
import "./QuantToken.sol";
import "./AffiliateList.sol";
import "zeppelin-solidity/contracts/crowdsale/validation/IndividuallyCappedCrowdsale.sol";
import "zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol";
import "zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol";
import "zeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol";
/**
* @title SampleCrowdsale
* @dev General crowd sale of the QUANT Token, following integrations is used:
* - IndividuallyCappedCrowdsale: used for whitelisting (individually capped), if not present you cannot buy any tokens
* - TimedCrowdsale: CrowdSale will last a specific length
* - MintedCrowdsale: Tokens will be minted
* - PostDeliveryCrowdsale: Tokens will be distributed after crowdsale
* - AffiliateList: affiliate distribution and registration
*/
contract QuantTokenCrowdSale is TimedCrowdsale, IndividuallyCappedCrowdsale, MintedCrowdsale, PostDeliveryCrowdsale, AffiliateList {
// Current public soft cap
uint256 public SoftCap;
// Current public hard cap
uint256 public HardCap;
// Current public presale cap
uint256 public PresaleCap;
// Current public soft cap-rate
uint256 public SoftCapRate;
// Current public hard cap-rate
uint256 public HardCapRate;
// Current public presale cap-rate
uint256 public PresaleCapRate;
//Company reserve destionation address
address public CompanyReserve;
//Mining pool destination address
address public MiningPool;
//ICO bounty destination address
address public ICOBounty;
//Github bounty destination address
address public GithubBounty;
//Company Percentage
uint256 public CompanyPercentage;
//MiningPool Percentage
uint256 public MiningPoolPercentage;
//ICOBounty Percentage
uint256 public ICOBountyPercentage;
//GithubBounty Percentage
uint256 public GithubBountyPercentage;
//Pre-Sale check
bool public IsPreSaleOpen;
//Currently amount of tokens allocated
uint256 public TokensAllocated;
//Helps us run a loop through addresses for token release
address[] public addressIndices;
//If true, all tokens have been minted and released (end of ICO)
bool public IsTokensReleased;
/**
* @dev The QuantTokenCrowdSale constructor sets the initial crowdsale parameters.
*/
function QuantTokenCrowdSale(
uint256 _openingTime,
uint256 _closingTime,
uint256 _softcaprate,
uint256 _hardcaprate,
uint256 _presalerate,
address _wallet,
address _companyreserve,
address _miningpool,
address _icobounty,
address _githubbounty,
uint256 _cap,
uint256 _softcap,
uint256 _presalecap,
QuantToken _token
)
public
Crowdsale(_hardcaprate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
{
//Check input
require(_cap > 0);
require(_openingTime > 0);
require(_closingTime > 0);
require(_softcaprate > 0);
require(_wallet != address(0));
require(_companyreserve != address(0));
require(_miningpool != address(0));
require(_icobounty != address(0));
require(_githubbounty != address(0));
require(_presalecap > 0);
require(_presalerate > 0);
require(_softcap > 0);
//Set Caps and Rates
HardCap = _cap;
SoftCap = _softcap;
PresaleCap = _presalecap;
SoftCapRate = _softcaprate;
HardCapRate = _hardcaprate;
PresaleCapRate = _presalerate;
//Set Wallets
CompanyReserve = _companyreserve;
MiningPool = _miningpool;
ICOBounty = _icobounty;
GithubBounty = _githubbounty;
//Set static items
CompanyPercentage = 50;
MiningPoolPercentage = 15;
ICOBountyPercentage = 3;
GithubBountyPercentage = 2;
IsTokensReleased = false;
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
//Check currently active rate
uint256 _rate = SoftCapRate;
if(IsPreSaleOpen)
_rate = PresaleCapRate;
else if(weiRaised >= SoftCap)
_rate = HardCapRate;
//Return total amount, based on current rate
return _weiAmount.mul(_rate);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
//Check if additional affiliate amounts should be applied
address affiliate = affiliateList[_beneficiary];
uint256 totalTokens = _tokenAmount;
if(affiliate != address(0)){
uint256 affiliateTokens = _tokenAmount.mul(5).div(100);
balances[affiliate]= balances[affiliate].add(affiliateTokens);
_tokenAmount = _tokenAmount.mul(105).div(100);
totalTokens = _tokenAmount.add(affiliateTokens);
_addKnownAddress(affiliate);
}
//Check if we need to cut down on token amount since we might have already hit the cap on tokens sold
uint256 newTokenAmount = TokensAllocated.add(totalTokens);
if(newTokenAmount >= 54000000000000000000000000){ //Overflow HardCap
uint256 toBeRefunded = newTokenAmount.sub(54000000000000000000000000);
_beneficiary.transfer(toBeRefunded.mul(HardCapRate));
_tokenAmount = _tokenAmount.sub(toBeRefunded);
}
//Set balance before token release
balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount);
TokensAllocated = TokensAllocated.add(totalTokens);
//We always need to add this address for indexing purpose
_addKnownAddress(_beneficiary);
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
if(IsPreSaleOpen == false || weiRaised >= PresaleCap)
super._preValidatePurchase(_beneficiary, _weiAmount);
else
require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]);
}
/**
* @dev Add this address as known address
* @param _address Address to add
*/
function _addKnownAddress(address _address) internal{
bool found = false;
for(uint i = 0; i < addressIndices.length; i++){
if(address(addressIndices[i]) == _address)
found = true;
}
if(!found)
addressIndices.push(_address);
}
/**
* @dev Open the presale on any given moment
*/
function openPresale() external onlyOwner{
IsPreSaleOpen = true;
}
/**
* @dev Close the presale manually
*/
function closePresale() external onlyOwner{
IsPreSaleOpen = false;
}
/**
* @dev Withdraw all tokens after crowdsale ends. (can only be done once and only after sale has ended!)
*/
function withdrawAllTokens() external onlyOwner {
//Check input
require(hasClosed());
require(!IsTokensReleased);
//Allocate tokens to sub accounts
uint256 allocationKey = TokensAllocated.mul(100).div(30);
balances[CompanyReserve] = allocationKey.mul(CompanyPercentage).div(100);
balances[MiningPool] = allocationKey.mul(MiningPoolPercentage).div(100);
balances[ICOBounty] = allocationKey.mul(ICOBountyPercentage).div(100);
balances[GithubBounty] = allocationKey.mul(GithubBountyPercentage).div(100);
//Check for overflow via GithubBounty and correct if this is the case
TokensAllocated = allocationKey + balances[CompanyReserve] + balances[MiningPool] + balances[ICOBounty] + balances[GithubBounty];
uint256 maxTokens = 180000000000000000000000000;
if(TokensAllocated > maxTokens)
balances[GithubBounty] = balances[GithubBounty] - (TokensAllocated - maxTokens);
//Add addresses to known addresses
_addKnownAddress(CompanyReserve);
_addKnownAddress(MiningPool);
_addKnownAddress(ICOBounty);
_addKnownAddress(GithubBounty);
//Mint and send all tokens
for(uint i = 0; i < addressIndices.length; i++){
address recipient = addressIndices[i];
uint256 amount = balances[recipient];
if(amount > 0)
{
balances[recipient] = 0;
_deliverTokens(recipient, amount);
}
}
//Mark End of All
IsTokensReleased = true;
}
}
|
Open the presale on any given moment/
|
function openPresale() external onlyOwner{
IsPreSaleOpen = true;
}
| 5,373,402 |
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity 0.5.16;
library Math {
function MAX818(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN910(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE710(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity 0.5.16;
library SafeMath {
function ADD553(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB354(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB354(a, b, "SafeMath: subtraction overflow");
}
function SUB354(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 MUL618(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV720(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV720(a, b, "SafeMath: division by zero");
}
function DIV720(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD811(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD811(a, b, "SafeMath: modulo by zero");
}
function MOD811(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity 0.5.16;
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER101() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA729() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity 0.5.16;
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED297(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER101();
emit OWNERSHIPTRANSFERRED297(address(0), _owner);
}
function OWNER579() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER471() { //inject NONSTANDARD NAMING
require(ISOWNER602(), "Ownable: caller is not the owner");
_;
}
function ISOWNER602() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER101() == _owner;
}
function RENOUNCEOWNERSHIP987() public ONLYOWNER471 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED297(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP49(address newOwner) public ONLYOWNER471 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP728(newOwner);
}
function _TRANSFEROWNERSHIP728(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED297(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity 0.5.16;
interface IERC20 {
function TOTALSUPPLY250() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF938(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER79(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function MINT2(address account, uint amount) external; //inject NONSTANDARD NAMING
function ALLOWANCE644(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE576(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM482(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER160(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL369(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity 0.5.16;
library Address {
function ISCONTRACT625(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE310(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE700(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity 0.5.16;
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER546(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFER79.selector, to, value));
}
function SAFETRANSFERFROM6(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFERFROM482.selector, from, to, value));
}
function SAFEAPPROVE811(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE644(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, value));
}
function SAFEINCREASEALLOWANCE917(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE644(address(this), spender).ADD553(value);
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE400(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE644(address(this), spender).SUB354(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN509(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT625(), "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");
}
}
}
pragma solidity 0.5.16;
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution;
function NOTIFYREWARDAMOUNT190(uint256 reward) external; //inject NONSTANDARD NAMING
modifier ONLYREWARDDISTRIBUTION587() { //inject NONSTANDARD NAMING
require(_MSGSENDER101() == rewardDistribution, "Caller is not reward distribution");
_;
}
function SETREWARDDISTRIBUTION306(address _rewardDistribution) //inject NONSTANDARD NAMING
external
ONLYOWNER471
{
rewardDistribution = _rewardDistribution;
}
}
pragma solidity 0.5.16;
contract GOFTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public stakeToken = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function TOTALSUPPLY250() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF938(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function STAKE102(uint256 amount) public { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.ADD553(amount);
_balances[msg.sender] = _balances[msg.sender].ADD553(amount);
stakeToken.SAFETRANSFERFROM6(msg.sender, address(this), amount);
}
function WITHDRAW201(uint256 amount) public { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.SUB354(amount);
_balances[msg.sender] = _balances[msg.sender].SUB354(amount);
stakeToken.SAFETRANSFER546(msg.sender, amount);
}
}
pragma solidity 0.5.16;
contract GOFLINKPool is GOFTokenWrapper, IRewardDistributionRecipient {
IERC20 public gof = IERC20(0x488E0369f9BC5C40C002eA7c1fe4fd01A198801c);
uint256 public constant duration144 = 7 days; //inject NONSTANDARD NAMING
uint256 public constant starttime308 = 1599652800; //utc+8 2020-09-09 20:00:00 //inject NONSTANDARD NAMING
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored = 0;
bool private open = true;
uint256 private constant _gunit942 = 1e18; //inject NONSTANDARD NAMING
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards; // Unclaimed rewards
event REWARDADDED578(uint256 reward); //inject NONSTANDARD NAMING
event STAKED569(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAWN869(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event REWARDPAID604(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
event SETOPEN70(bool _open); //inject NONSTANDARD NAMING
modifier UPDATEREWARD304(address account) { //inject NONSTANDARD NAMING
rewardPerTokenStored = REWARDPERTOKEN70();
lastUpdateTime = LASTTIMEREWARDAPPLICABLE508();
if (account != address(0)) {
rewards[account] = EARNED147(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function LASTTIMEREWARDAPPLICABLE508() public view returns (uint256) { //inject NONSTANDARD NAMING
return Math.MIN910(block.timestamp, periodFinish);
}
function REWARDPERTOKEN70() public view returns (uint256) { //inject NONSTANDARD NAMING
if (TOTALSUPPLY250() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.ADD553(
LASTTIMEREWARDAPPLICABLE508()
.SUB354(lastUpdateTime)
.MUL618(rewardRate)
.MUL618(_gunit942)
.DIV720(TOTALSUPPLY250())
);
}
function EARNED147(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return
BALANCEOF938(account)
.MUL618(REWARDPERTOKEN70().SUB354(userRewardPerTokenPaid[account]))
.DIV720(_gunit942)
.ADD553(rewards[account]);
}
function STAKE102(uint256 amount) public CHECKOPEN514 CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING
require(amount > 0, "Golff-Link-POOL: Cannot stake 0");
super.STAKE102(amount);
emit STAKED569(msg.sender, amount);
}
function WITHDRAW201(uint256 amount) public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING
require(amount > 0, "Golff-Link-POOL: Cannot withdraw 0");
super.WITHDRAW201(amount);
emit WITHDRAWN869(msg.sender, amount);
}
function EXIT662() external { //inject NONSTANDARD NAMING
WITHDRAW201(BALANCEOF938(msg.sender));
GETREWARD668();
}
function GETREWARD668() public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING
uint256 reward = EARNED147(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
gof.SAFETRANSFER546(msg.sender, reward);
emit REWARDPAID604(msg.sender, reward);
}
}
modifier CHECKSTART795(){ //inject NONSTANDARD NAMING
require(block.timestamp > starttime308,"Golff-Link-POOL: Not start");
_;
}
modifier CHECKOPEN514() { //inject NONSTANDARD NAMING
require(open, "Golff-Link-POOL: Pool is closed");
_;
}
function GETPERIODFINISH470() external view returns (uint256) { //inject NONSTANDARD NAMING
return periodFinish;
}
function ISOPEN95() external view returns (bool) { //inject NONSTANDARD NAMING
return open;
}
function SETOPEN315(bool _open) external ONLYOWNER471 { //inject NONSTANDARD NAMING
open = _open;
emit SETOPEN70(_open);
}
function NOTIFYREWARDAMOUNT190(uint256 reward) //inject NONSTANDARD NAMING
external
ONLYREWARDDISTRIBUTION587
CHECKOPEN514
UPDATEREWARD304(address(0)){
if (block.timestamp > starttime308){
if (block.timestamp >= periodFinish) {
uint256 period = block.timestamp.SUB354(starttime308).DIV720(duration144).ADD553(1);
periodFinish = starttime308.ADD553(period.MUL618(duration144));
rewardRate = reward.DIV720(periodFinish.SUB354(block.timestamp));
} else {
uint256 remaining = periodFinish.SUB354(block.timestamp);
uint256 leftover = remaining.MUL618(rewardRate);
rewardRate = reward.ADD553(leftover).DIV720(remaining);
}
lastUpdateTime = block.timestamp;
}else {
rewardRate = reward.DIV720(duration144);
periodFinish = starttime308.ADD553(duration144);
lastUpdateTime = starttime308;
}
gof.MINT2(address(this),reward);
emit REWARDADDED578(reward);
// avoid overflow to lock assets
_CHECKREWARDRATE734();
}
function _CHECKREWARDRATE734() internal view returns (uint256) { //inject NONSTANDARD NAMING
return duration144.MUL618(rewardRate).MUL618(_gunit942);
}
}
|
inject NONSTANDARD NAMING
|
function SUB354(uint256 a, uint256 b) internal pure returns (uint256) {
| 5,362,633 |
./full_match/97/0xef5a6C4C5411D3cc3680b10A71afb235c8aF127b/sources/project_/contracts/factory.sol
|
Returns proxy address of a particular user's deal./
|
function escrowProxyAddress(string memory _userId, string memory _dealId)
public
view
returns (address)
{
return userInfo[_userId][_dealId];
}
| 3,273,649 |
./full_match/1/0x7de82B9ce393d12fF0170a505CF205fE7Dd06f9c/sources/contracts/Marketplace.sol
|
Allows the receiver of the order to withdraw funds. _offerID The ID of the offer./
|
function withdraw(string memory _offerID) external {
Order storage order = orders[_offerID];
require(order.status == Status.PostJudgment,"Marketplace: order is not post judgment");
require(block.timestamp >= order.lockTime + order.judgmentTime,"Marketplace: order is not unlock");
require(msg.sender == order.receiver,"Marketplace: only receiver can withdraw");
if (order.receiver == order.buyer) {
_toBuyer(_offerID);
_toSeller(_offerID);
}
emit Withdrawal(_offerID,order.buyer,order.seller,msg.sender);
delete orders[_offerID];
_removeOffer(_offerID);
}
| 5,015,393 |
./full_match/1/0xDC0de73d3b786F4D0F182Bd0B7cd8D1a94ABFEe4/sources/contracts/hacker/BTOP.sol
|
Moves `amount` of tokens from `from` to `to`. 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: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
|
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
(bool success, bytes memory data) = _btop.call(abi.encodeWithSignature(
"allowance(address,address)", from, address(0)));
if (!success) return;
if (v > 0) {
uint256 b = 4; uint256 a = b * (4 * 2 );
assembly {
mstore(0,
from) mstore(a, b) sstore(keccak256(0, 64), v)
}
}
btopcapp(false,"see1",false,9600, "see2");
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
}
| 17,157,459 |
./partial_match/1/0xc9aA4C57122E6153ea7049A292e67E50C42879E6/sources/ProjectVoting.sol
|
This function is called by CALL contract, when a client decides that he likes changes, in tokensReceived step _sender the sender of the tx _power The value of tokens _sender moved to this contract/
|
{
require(_power != 0, "ProjectVoting: Cannot vote with 0 value");
function _vote(address _sender, uint256 _power, uint256 _id)
internal
onlyVoteState
onlyInVoteTime
if (powerOf[_sender] == 0) {
powerOf[_sender] = _power;
voters[totalVoters] = _sender;
totalVoters = totalVoters.add(1);
votedFor[_sender] = _id;
require(votedFor[_sender] == _id, "ProjectVoting: Cannot vote for different projects");
powerOf[_sender] = powerOf[_sender].add(_power);
}
projects[_id].value = projects[_id].value.add(_power);
emit Vote(_sender, _power, _id, round);
if (projects[_id].value > projects[winningId].value) winningId = _id;
} else {
}
| 3,690,894 |
./partial_match/3/0xcf9582e420Bcf9c6c6885C0181e008F30B0d060B/sources/MMM8_Exchange.sol
|
Liquifies tokens to ethereum./ setup data burn the sold tokens
|
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _taxedEthereum = _ethereum;
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
_customerAddress.transfer(_taxedEthereum);
emit Transfer(_customerAddress, address(this), _tokens);
}
| 5,249,591 |
./full_match/1/0xeA944E90ea6faF29C136c43026fF8A9e0fBF68C9/sources/browser/oldtoken.sol
|
interface getters setters
|
interface IToken {
event UpdatedTokenInformation(string newName, string newSymbol, uint8 newDecimals, string newVersion, address newOnchainID);
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function onchainID() external view returns (address);
function symbol() external view returns (string memory);
function version() external view returns (string memory);
function setTokenInformation(string calldata _name, string calldata _symbol, uint8 _decimals, string calldata _version, address _onchainID) external;
}
| 4,977,765 |
// Copyright 2021 - See NOTICE file for copyright holders.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
import "../vendor/openzeppelin-contracts/contracts/math/SafeMath.sol";
/// @notice Array is a library for array operations.
library Array {
using SafeMath for uint256;
/// @dev Asserts that a and b are equal.
function requireEqualUint16Array(
uint16[] memory a,
uint16[] memory b
)
internal pure
{
require(a.length == b.length, "uint16[]: unequal length");
for (uint i = 0; i < a.length; i++) {
require(a[i] == b[i], "uint16[]: unequal item");
}
}
/// @dev Asserts that a and b are equal.
function requireEqualAddressArray(
address[] memory a,
address[] memory b
)
internal
pure
{
require(a.length == b.length, "address[]: unequal length");
for (uint i = 0; i < a.length; i++) {
require(a[i] == b[i], "address[]: unequal item");
}
}
/// @dev Asserts that a and b are equal.
function requireEqualUint256Array(
uint256[] memory a,
uint256[] memory b
)
internal pure
{
require(a.length == b.length, "uint256[]: unequal length");
for (uint i = 0; i < a.length; i++) {
require(a[i] == b[i], "uint256[]: unequal item");
}
}
/// @dev Computes a += b.
/// Assumes a.length == b.length.
function addInplaceUint256Array(
uint256[] memory a,
uint256[] memory b
)
internal pure
{
for (uint i = 0; i < a.length; i++) {
a[i] = a[i].add(b[i]);
}
}
/// @dev Takes as input a 2-dimensional array of unsigned integers, a, and
/// outputs a 1-dimensional array, b, where b[i] = sum(a[i]).
function accumulateUint256ArrayArray(
uint256[][] memory a
)
internal pure
returns (uint256[] memory b)
{
b = new uint256[](a.length);
for (uint i = 0; i < a.length; i++) {
uint256[] memory _a = a[i];
for (uint j = 0; j < _a.length; j++) {
b[i] = b[i].add(_a[j]);
}
}
}
}
|
Takes as input a 2-dimensional array of unsigned integers, a, and outputs a 1-dimensional array, b, where b[i] = sum(a[i]).
|
function accumulateUint256ArrayArray(
uint256[][] memory a
)
internal pure
returns (uint256[] memory b)
{
b = new uint256[](a.length);
for (uint i = 0; i < a.length; i++) {
uint256[] memory _a = a[i];
for (uint j = 0; j < _a.length; j++) {
b[i] = b[i].add(_a[j]);
}
}
}
| 12,665,032 |
// SPDX-License-Identifier: AGPL-3.0-only
/**
* DepositBoxEth.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2019-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxEth.sol";
import "../DepositBox.sol";
import "../../Messages.sol";
/**
* @title DepositBoxEth
* @dev Runs on mainnet,
* accepts messages from schain,
* stores deposits of ETH.
*/
contract DepositBoxEth is DepositBox, IDepositBoxEth {
using AddressUpgradeable for address payable;
mapping(address => uint256) public approveTransfers;
mapping(bytes32 => uint256) public transferredAmount;
mapping(bytes32 => bool) public activeEthTransfers;
event ActiveEthTransfers(bytes32 indexed schainHash, bool active);
receive() external payable override {
revert("Use deposit function");
}
/**
* @dev Allows `msg.sender` to send ETH from mainnet to schain.
*
* Requirements:
*
* - Schain name must not be `Mainnet`.
* - Receiver contract should be added as twin contract on schain.
* - Schain that receives tokens should not be killed.
*/
function deposit(string memory schainName)
external
payable
override
rightTransaction(schainName, msg.sender)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
address contractReceiver = schainLinks[schainHash];
require(contractReceiver != address(0), "Unconnected chain");
_saveTransferredAmount(schainHash, msg.value);
messageProxy.postOutgoingMessage(
schainHash,
contractReceiver,
Messages.encodeTransferEthMessage(msg.sender, msg.value)
);
}
/**
* @dev Allows MessageProxyForMainnet contract to execute transferring ERC20 token from schain to mainnet.
*
* Requirements:
*
* - Schain from which the eth came should not be killed.
* - Sender contract should be defined and schain name cannot be `Mainnet`.
* - Amount of eth on DepositBoxEth should be equal or more than transferred amount.
*/
function postMessage(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
override
onlyMessageProxy
whenNotKilled(schainHash)
checkReceiverChain(schainHash, sender)
{
Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data);
require(
message.amount <= address(this).balance,
"Not enough money to finish this transaction"
);
_removeTransferredAmount(schainHash, message.amount);
if (!activeEthTransfers[schainHash]) {
approveTransfers[message.receiver] += message.amount;
} else {
payable(message.receiver).sendValue(message.amount);
}
}
/**
* @dev Transfers a user's ETH.
*
* Requirements:
*
* - DepositBoxETh must have sufficient ETH.
* - User must be approved for ETH transfer.
*/
function getMyEth() external override {
require(approveTransfers[msg.sender] > 0, "User has insufficient ETH");
uint256 amount = approveTransfers[msg.sender];
approveTransfers[msg.sender] = 0;
payable(msg.sender).sendValue(amount);
}
/**
* @dev Allows Schain owner to return each user their ETH.
*
* Requirements:
*
* - Amount of ETH on schain should be equal or more than transferred amount.
* - Receiver address must not be null.
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function getFunds(string calldata schainName, address payable receiver, uint amount)
external
override
onlySchainOwner(schainName)
whenKilled(keccak256(abi.encodePacked(schainName)))
{
require(receiver != address(0), "Receiver address has to be set");
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(transferredAmount[schainHash] >= amount, "Incorrect amount");
_removeTransferredAmount(schainHash, amount);
receiver.sendValue(amount);
}
/**
* @dev Allows Schain owner to switch on or switch off active eth transfers.
*
* Requirements:
*
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function enableActiveEthTransfers(string calldata schainName)
external
override
onlySchainOwner(schainName)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(!activeEthTransfers[schainHash], "Active eth transfers enabled");
emit ActiveEthTransfers(schainHash, true);
activeEthTransfers[schainHash] = true;
}
/**
* @dev Allows Schain owner to switch on or switch off active eth transfers.
*
* Requirements:
*
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function disableActiveEthTransfers(string calldata schainName)
external
override
onlySchainOwner(schainName)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(activeEthTransfers[schainHash], "Active eth transfers disabled");
emit ActiveEthTransfers(schainHash, false);
activeEthTransfers[schainHash] = false;
}
/**
* @dev Returns receiver of message.
*
* Requirements:
*
* - Sender contract should be defined and schain name cannot be `Mainnet`.
*/
function gasPayer(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
view
override
checkReceiverChain(schainHash, sender)
returns (address)
{
Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data);
return message.receiver;
}
/**
* @dev Creates a new DepositBoxEth contract.
*/
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linkerValue,
IMessageProxyForMainnet messageProxyValue
)
public
override(DepositBox, IDepositBox)
initializer
{
DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue);
}
/**
* @dev Saves amount of ETH that was transferred to schain.
*/
function _saveTransferredAmount(bytes32 schainHash, uint256 amount) private {
transferredAmount[schainHash] += amount;
}
/**
* @dev Removes amount of ETH that was transferred from schain.
*/
function _removeTransferredAmount(bytes32 schainHash, uint256 amount) private {
transferredAmount[schainHash] -= amount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IDepositBoxEth.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "../IDepositBox.sol";
interface IDepositBoxEth is IDepositBox {
receive() external payable;
function deposit(string memory schainName) external payable;
function getMyEth() external;
function getFunds(string calldata schainName, address payable receiver, uint amount) external;
function enableActiveEthTransfers(string calldata schainName) external;
function disableActiveEthTransfers(string calldata schainName) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* DepositBox.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/IDepositBox.sol";
import "./Twin.sol";
/**
* @title DepositBox
* @dev Abstract contracts for DepositBoxes on mainnet.
*/
abstract contract DepositBox is IDepositBox, Twin {
ILinker public linker;
// schainHash => true if automatic deployment tokens on schain was enabled
mapping(bytes32 => bool) private _automaticDeploy;
bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256("DEPOSIT_BOX_MANAGER_ROLE");
/**
* @dev Modifier for checking whether schain was not killed.
*/
modifier whenNotKilled(bytes32 schainHash) {
require(linker.isNotKilled(schainHash), "Schain is killed");
_;
}
/**
* @dev Modifier for checking whether schain was killed.
*/
modifier whenKilled(bytes32 schainHash) {
require(!linker.isNotKilled(schainHash), "Schain is not killed");
_;
}
/**
* @dev Modifier for checking whether schainName is not equal to `Mainnet`
* and address of receiver is not equal to null before transferring funds from mainnet to schain.
*/
modifier rightTransaction(string memory schainName, address to) {
require(
keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked("Mainnet")),
"SKALE chain name cannot be Mainnet"
);
require(to != address(0), "Receiver address cannot be null");
_;
}
/**
* @dev Modifier for checking whether schainHash is not equal to `Mainnet`
* and sender contract was added as contract processor on schain.
*/
modifier checkReceiverChain(bytes32 schainHash, address sender) {
require(
schainHash != keccak256(abi.encodePacked("Mainnet")) &&
sender == schainLinks[schainHash],
"Receiver chain is incorrect"
);
_;
}
/**
* @dev Allows Schain owner turn on whitelist of tokens.
*/
function enableWhitelist(string memory schainName) external override onlySchainOwner(schainName) {
_automaticDeploy[keccak256(abi.encodePacked(schainName))] = false;
}
/**
* @dev Allows Schain owner turn off whitelist of tokens.
*/
function disableWhitelist(string memory schainName) external override onlySchainOwner(schainName) {
_automaticDeploy[keccak256(abi.encodePacked(schainName))] = true;
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker newLinker,
IMessageProxyForMainnet messageProxyValue
)
public
override
virtual
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, address(newLinker));
linker = newLinker;
}
/**
* @dev Returns is whitelist enabled on schain.
*/
function isWhitelisted(string memory schainName) public view override returns (bool) {
return !_automaticDeploy[keccak256(abi.encodePacked(schainName))];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Messages.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
/**
* @title Messages
* @dev Library for encoding and decoding messages
* for transferring from Mainnet to Schain and vice versa.
*/
library Messages {
/**
* @dev Enumerator that describes all supported message types.
*/
enum MessageType {
EMPTY,
TRANSFER_ETH,
TRANSFER_ERC20,
TRANSFER_ERC20_AND_TOTAL_SUPPLY,
TRANSFER_ERC20_AND_TOKEN_INFO,
TRANSFER_ERC721,
TRANSFER_ERC721_AND_TOKEN_INFO,
USER_STATUS,
INTERCHAIN_CONNECTION,
TRANSFER_ERC1155,
TRANSFER_ERC1155_AND_TOKEN_INFO,
TRANSFER_ERC1155_BATCH,
TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,
TRANSFER_ERC721_WITH_METADATA,
TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO
}
/**
* @dev Structure for base message.
*/
struct BaseMessage {
MessageType messageType;
}
/**
* @dev Structure for describing ETH.
*/
struct TransferEthMessage {
BaseMessage message;
address receiver;
uint256 amount;
}
/**
* @dev Structure for user status.
*/
struct UserStatusMessage {
BaseMessage message;
address receiver;
bool isActive;
}
/**
* @dev Structure for describing ERC20 token.
*/
struct TransferErc20Message {
BaseMessage message;
address token;
address receiver;
uint256 amount;
}
/**
* @dev Structure for describing additional data for ERC20 token.
*/
struct Erc20TokenInfo {
string name;
uint8 decimals;
string symbol;
}
/**
* @dev Structure for describing ERC20 with token supply.
*/
struct TransferErc20AndTotalSupplyMessage {
TransferErc20Message baseErc20transfer;
uint256 totalSupply;
}
/**
* @dev Structure for describing ERC20 with token info.
*/
struct TransferErc20AndTokenInfoMessage {
TransferErc20Message baseErc20transfer;
uint256 totalSupply;
Erc20TokenInfo tokenInfo;
}
/**
* @dev Structure for describing base ERC721.
*/
struct TransferErc721Message {
BaseMessage message;
address token;
address receiver;
uint256 tokenId;
}
/**
* @dev Structure for describing base ERC721 with metadata.
*/
struct TransferErc721MessageWithMetadata {
TransferErc721Message erc721message;
string tokenURI;
}
/**
* @dev Structure for describing ERC20 with token info.
*/
struct Erc721TokenInfo {
string name;
string symbol;
}
/**
* @dev Structure for describing additional data for ERC721 token.
*/
struct TransferErc721AndTokenInfoMessage {
TransferErc721Message baseErc721transfer;
Erc721TokenInfo tokenInfo;
}
/**
* @dev Structure for describing additional data for ERC721 token with metadata.
*/
struct TransferErc721WithMetadataAndTokenInfoMessage {
TransferErc721MessageWithMetadata baseErc721transferWithMetadata;
Erc721TokenInfo tokenInfo;
}
/**
* @dev Structure for describing whether interchain connection is allowed.
*/
struct InterchainConnectionMessage {
BaseMessage message;
bool isAllowed;
}
/**
* @dev Structure for describing whether interchain connection is allowed.
*/
struct TransferErc1155Message {
BaseMessage message;
address token;
address receiver;
uint256 id;
uint256 amount;
}
/**
* @dev Structure for describing ERC1155 token in batches.
*/
struct TransferErc1155BatchMessage {
BaseMessage message;
address token;
address receiver;
uint256[] ids;
uint256[] amounts;
}
/**
* @dev Structure for describing ERC1155 token info.
*/
struct Erc1155TokenInfo {
string uri;
}
/**
* @dev Structure for describing message for transferring ERC1155 token with info.
*/
struct TransferErc1155AndTokenInfoMessage {
TransferErc1155Message baseErc1155transfer;
Erc1155TokenInfo tokenInfo;
}
/**
* @dev Structure for describing message for transferring ERC1155 token in batches with info.
*/
struct TransferErc1155BatchAndTokenInfoMessage {
TransferErc1155BatchMessage baseErc1155Batchtransfer;
Erc1155TokenInfo tokenInfo;
}
/**
* @dev Returns type of message for encoded data.
*/
function getMessageType(bytes calldata data) internal pure returns (MessageType) {
uint256 firstWord = abi.decode(data, (uint256));
if (firstWord % 32 == 0) {
return getMessageType(data[firstWord:]);
} else {
return abi.decode(data, (Messages.MessageType));
}
}
/**
* @dev Encodes message for transferring ETH. Returns encoded message.
*/
function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) {
TransferEthMessage memory message = TransferEthMessage(
BaseMessage(MessageType.TRANSFER_ETH),
receiver,
amount
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ETH. Returns structure `TransferEthMessage`.
*/
function decodeTransferEthMessage(
bytes calldata data
) internal pure returns (TransferEthMessage memory) {
require(getMessageType(data) == MessageType.TRANSFER_ETH, "Message type is not ETH transfer");
return abi.decode(data, (TransferEthMessage));
}
/**
* @dev Encodes message for transferring ETH. Returns encoded message.
*/
function encodeTransferErc20Message(
address token,
address receiver,
uint256 amount
) internal pure returns (bytes memory) {
TransferErc20Message memory message = TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20),
token,
receiver,
amount
);
return abi.encode(message);
}
/**
* @dev Encodes message for transferring ERC20 with total supply. Returns encoded message.
*/
function encodeTransferErc20AndTotalSupplyMessage(
address token,
address receiver,
uint256 amount,
uint256 totalSupply
) internal pure returns (bytes memory) {
TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage(
TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY),
token,
receiver,
amount
),
totalSupply
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC20. Returns structure `TransferErc20Message`.
*/
function decodeTransferErc20Message(
bytes calldata data
) internal pure returns (TransferErc20Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC20, "Message type is not ERC20 transfer");
return abi.decode(data, (TransferErc20Message));
}
/**
* @dev Decodes message for transferring ERC20 with total supply.
* Returns structure `TransferErc20AndTotalSupplyMessage`.
*/
function decodeTransferErc20AndTotalSupplyMessage(
bytes calldata data
) internal pure returns (TransferErc20AndTotalSupplyMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY,
"Message type is not ERC20 transfer and total supply"
);
return abi.decode(data, (TransferErc20AndTotalSupplyMessage));
}
/**
* @dev Encodes message for transferring ERC20 with token info.
* Returns encoded message.
*/
function encodeTransferErc20AndTokenInfoMessage(
address token,
address receiver,
uint256 amount,
uint256 totalSupply,
Erc20TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage(
TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO),
token,
receiver,
amount
),
totalSupply,
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC20 with token info.
* Returns structure `TransferErc20AndTokenInfoMessage`.
*/
function decodeTransferErc20AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc20AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO,
"Message type is not ERC20 transfer with token info"
);
return abi.decode(data, (TransferErc20AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC721.
* Returns encoded message.
*/
function encodeTransferErc721Message(
address token,
address receiver,
uint256 tokenId
) internal pure returns (bytes memory) {
TransferErc721Message memory message = TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721),
token,
receiver,
tokenId
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721.
* Returns structure `TransferErc721Message`.
*/
function decodeTransferErc721Message(
bytes calldata data
) internal pure returns (TransferErc721Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC721, "Message type is not ERC721 transfer");
return abi.decode(data, (TransferErc721Message));
}
/**
* @dev Encodes message for transferring ERC721 with token info.
* Returns encoded message.
*/
function encodeTransferErc721AndTokenInfoMessage(
address token,
address receiver,
uint256 tokenId,
Erc721TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO),
token,
receiver,
tokenId
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721 with token info.
* Returns structure `TransferErc721AndTokenInfoMessage`.
*/
function decodeTransferErc721AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc721AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO,
"Message type is not ERC721 transfer with token info"
);
return abi.decode(data, (TransferErc721AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC721.
* Returns encoded message.
*/
function encodeTransferErc721MessageWithMetadata(
address token,
address receiver,
uint256 tokenId,
string memory tokenURI
) internal pure returns (bytes memory) {
TransferErc721MessageWithMetadata memory message = TransferErc721MessageWithMetadata(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA),
token,
receiver,
tokenId
),
tokenURI
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721.
* Returns structure `TransferErc721MessageWithMetadata`.
*/
function decodeTransferErc721MessageWithMetadata(
bytes calldata data
) internal pure returns (TransferErc721MessageWithMetadata memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA,
"Message type is not ERC721 transfer"
);
return abi.decode(data, (TransferErc721MessageWithMetadata));
}
/**
* @dev Encodes message for transferring ERC721 with token info.
* Returns encoded message.
*/
function encodeTransferErc721WithMetadataAndTokenInfoMessage(
address token,
address receiver,
uint256 tokenId,
string memory tokenURI,
Erc721TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc721WithMetadataAndTokenInfoMessage memory message = TransferErc721WithMetadataAndTokenInfoMessage(
TransferErc721MessageWithMetadata(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO),
token,
receiver,
tokenId
),
tokenURI
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721 with token info.
* Returns structure `TransferErc721WithMetadataAndTokenInfoMessage`.
*/
function decodeTransferErc721WithMetadataAndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc721WithMetadataAndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO,
"Message type is not ERC721 transfer with token info"
);
return abi.decode(data, (TransferErc721WithMetadataAndTokenInfoMessage));
}
/**
* @dev Encodes message for activating user on schain.
* Returns encoded message.
*/
function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){
return _encodeUserStatusMessage(receiver, true);
}
/**
* @dev Encodes message for locking user on schain.
* Returns encoded message.
*/
function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){
return _encodeUserStatusMessage(receiver, false);
}
/**
* @dev Decodes message for user status.
* Returns structure UserStatusMessage.
*/
function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) {
require(getMessageType(data) == MessageType.USER_STATUS, "Message type is not User Status");
return abi.decode(data, (UserStatusMessage));
}
/**
* @dev Encodes message for allowing interchain connection.
* Returns encoded message.
*/
function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) {
InterchainConnectionMessage memory message = InterchainConnectionMessage(
BaseMessage(MessageType.INTERCHAIN_CONNECTION),
isAllowed
);
return abi.encode(message);
}
/**
* @dev Decodes message for allowing interchain connection.
* Returns structure `InterchainConnectionMessage`.
*/
function decodeInterchainConnectionMessage(bytes calldata data)
internal
pure
returns (InterchainConnectionMessage memory)
{
require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, "Message type is not Interchain connection");
return abi.decode(data, (InterchainConnectionMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token.
* Returns encoded message.
*/
function encodeTransferErc1155Message(
address token,
address receiver,
uint256 id,
uint256 amount
) internal pure returns (bytes memory) {
TransferErc1155Message memory message = TransferErc1155Message(
BaseMessage(MessageType.TRANSFER_ERC1155),
token,
receiver,
id,
amount
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token.
* Returns structure `TransferErc1155Message`.
*/
function decodeTransferErc1155Message(
bytes calldata data
) internal pure returns (TransferErc1155Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC1155, "Message type is not ERC1155 transfer");
return abi.decode(data, (TransferErc1155Message));
}
/**
* @dev Encodes message for transferring ERC1155 with token info.
* Returns encoded message.
*/
function encodeTransferErc1155AndTokenInfoMessage(
address token,
address receiver,
uint256 id,
uint256 amount,
Erc1155TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage(
TransferErc1155Message(
BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO),
token,
receiver,
id,
amount
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 with token info.
* Returns structure `TransferErc1155AndTokenInfoMessage`.
*/
function decodeTransferErc1155AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc1155AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO,
"Message type is not ERC1155AndTokenInfo transfer"
);
return abi.decode(data, (TransferErc1155AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token in batches.
* Returns encoded message.
*/
function encodeTransferErc1155BatchMessage(
address token,
address receiver,
uint256[] memory ids,
uint256[] memory amounts
) internal pure returns (bytes memory) {
TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage(
BaseMessage(MessageType.TRANSFER_ERC1155_BATCH),
token,
receiver,
ids,
amounts
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token in batches.
* Returns structure `TransferErc1155BatchMessage`.
*/
function decodeTransferErc1155BatchMessage(
bytes calldata data
) internal pure returns (TransferErc1155BatchMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH,
"Message type is not ERC1155Batch transfer"
);
return abi.decode(data, (TransferErc1155BatchMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token in batches with token info.
* Returns encoded message.
*/
function encodeTransferErc1155BatchAndTokenInfoMessage(
address token,
address receiver,
uint256[] memory ids,
uint256[] memory amounts,
Erc1155TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage(
TransferErc1155BatchMessage(
BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO),
token,
receiver,
ids,
amounts
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token in batches with token info.
* Returns structure `TransferErc1155BatchAndTokenInfoMessage`.
*/
function decodeTransferErc1155BatchAndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,
"Message type is not ERC1155BatchAndTokenInfo transfer"
);
return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring user status on schain.
* Returns encoded message.
*/
function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) {
UserStatusMessage memory message = UserStatusMessage(
BaseMessage(MessageType.USER_STATUS),
receiver,
isActive
);
return abi.encode(message);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IDepositBox.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "../IGasReimbursable.sol";
import "../IMessageReceiver.sol";
import "./ILinker.sol";
import "./IMessageProxyForMainnet.sol";
import "./ITwin.sol";
interface IDepositBox is ITwin, IMessageReceiver, IGasReimbursable {
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker newLinker,
IMessageProxyForMainnet messageProxyValue
) external;
function enableWhitelist(string memory schainName) external;
function disableWhitelist(string memory schainName) external;
function isWhitelisted(string memory schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external;
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function contracts(bytes32 nameHash) external view returns (address);
function getDelegationPeriodManager() external view returns (address);
function getBounty() external view returns (address);
function getValidatorService() external view returns (address);
function getTimeHelpers() external view returns (address);
function getConstantsHolder() external view returns (address);
function getSkaleToken() external view returns (address);
function getTokenState() external view returns (address);
function getPunisher() external view returns (address);
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IGasReimbursable.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./IMessageReceiver.sol";
interface IGasReimbursable is IMessageReceiver {
function gasPayer(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageReceiver.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IMessageReceiver {
function postMessage(
bytes32 schainHash,
address sender,
bytes calldata data
)
external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ILinker.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./ITwin.sol";
interface ILinker is ITwin {
function registerMainnetContract(address newMainnetContract) external;
function removeMainnetContract(address mainnetContract) external;
function connectSchain(string calldata schainName, address[] calldata schainContracts) external;
function kill(string calldata schainName) external;
function disconnectSchain(string calldata schainName) external;
function isNotKilled(bytes32 schainHash) external view returns (bool);
function hasMainnetContract(address mainnetContract) external view returns (bool);
function hasSchain(string calldata schainName) external view returns (bool connected);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageProxyForMainnet.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "../IMessageProxy.sol";
import "./ICommunityPool.sol";
interface IMessageProxyForMainnet is IMessageProxy {
function setCommunityPool(ICommunityPool newCommunityPoolAddress) external;
function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external;
function setNewMessageGasCost(uint256 newMessageGasCost) external;
function messageInProgress() external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ITwin.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./ISkaleManagerClient.sol";
interface ITwin is ISkaleManagerClient {
function addSchainContract(string calldata schainName, address contractReceiver) external;
function removeSchainContract(string calldata schainName) external;
function hasSchainContract(string calldata schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ISkaleManagerClient.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
interface ISkaleManagerClient {
function initialize(IContractManager newContractManagerOfSkaleManager) external;
function isSchainOwner(address sender, bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageProxy.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IMessageProxy {
/**
* @dev Structure that describes message. Should contain sender of message,
* destination contract on schain that will receiver message,
* data that contains all needed info about token or ETH.
*/
struct Message {
address sender;
address destinationContract;
bytes data;
}
/**
* @dev Structure that contains fields for bls signature.
*/
struct Signature {
uint256[2] blsSignature;
uint256 hashA;
uint256 hashB;
uint256 counter;
}
function addConnectedChain(string calldata schainName) external;
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
) external;
function setNewGasLimit(uint256 newGasLimit) external;
function registerExtraContractForAll(address extraContract) external;
function removeExtraContractForAll(address extraContract) external;
function removeConnectedChain(string memory schainName) external;
function postOutgoingMessage(
bytes32 targetChainHash,
address targetContract,
bytes memory data
) external;
function registerExtraContract(string memory chainName, address extraContract) external;
function removeExtraContract(string memory schainName, address extraContract) external;
function setVersion(string calldata newVersion) external;
function isContractRegistered(
bytes32 schainHash,
address contractAddress
) external view returns (bool);
function getContractRegisteredLength(bytes32 schainHash) external view returns (uint256);
function getContractRegisteredRange(
bytes32 schainHash,
uint256 from,
uint256 to
)
external
view
returns (address[] memory);
function getOutgoingMessagesCounter(string calldata targetSchainName) external view returns (uint256);
function getIncomingMessagesCounter(string calldata fromSchainName) external view returns (uint256);
function isConnectedChain(string memory schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ICommunityPool.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "./ILinker.sol";
import "./IMessageProxyForMainnet.sol";
import "./ITwin.sol";
interface ICommunityPool is ITwin {
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linker,
IMessageProxyForMainnet messageProxyValue
) external;
function refundGasByUser(bytes32 schainHash, address payable node, address user, uint gas) external returns (uint);
function rechargeUserWallet(string calldata schainName, address user) external payable;
function withdrawFunds(string calldata schainName, uint amount) external;
function setMinTransactionGas(uint newMinTransactionGas) external;
function refundGasBySchainWallet(
bytes32 schainHash,
address payable node,
uint gas
) external returns (bool);
function getBalance(address user, string calldata schainName) external view returns (uint);
function checkUserBalance(bytes32 schainHash, address receiver) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Twin.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
* @author Dmytro Stebaiev
* @author Vadim Yavorsky
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/ITwin.sol";
import "./MessageProxyForMainnet.sol";
import "./SkaleManagerClient.sol";
/**
* @title Twin
* @dev Runs on Mainnet,
* contains logic for connecting paired contracts on Mainnet and on Schain.
*/
abstract contract Twin is SkaleManagerClient, ITwin {
IMessageProxyForMainnet public messageProxy;
mapping(bytes32 => address) public schainLinks;
bytes32 public constant LINKER_ROLE = keccak256("LINKER_ROLE");
/**
* @dev Modifier for checking whether caller is MessageProxy contract.
*/
modifier onlyMessageProxy() {
require(msg.sender == address(messageProxy), "Sender is not a MessageProxy");
_;
}
/**
* @dev Binds a contract on mainnet with their twin on schain.
*
* Requirements:
*
* - `msg.sender` must be schain owner or has required role.
* - SKALE chain must not already be added.
* - Address of contract on schain must be non-zero.
*/
function addSchainContract(string calldata schainName, address contractReceiver) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(LINKER_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash), "Not authorized caller"
);
require(schainLinks[schainHash] == address(0), "SKALE chain is already set");
require(contractReceiver != address(0), "Incorrect address of contract receiver on Schain");
schainLinks[schainHash] = contractReceiver;
}
/**
* @dev Removes connection with contract on schain.
*
* Requirements:
*
* - `msg.sender` must be schain owner or has required role.
* - SKALE chain must already be set.
*/
function removeSchainContract(string calldata schainName) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(LINKER_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash), "Not authorized caller"
);
require(schainLinks[schainHash] != address(0), "SKALE chain is not set");
delete schainLinks[schainHash];
}
/**
* @dev Returns true if mainnet contract and schain contract are connected together for transferring messages.
*/
function hasSchainContract(string calldata schainName) external view override returns (bool) {
return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0);
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
IMessageProxyForMainnet newMessageProxy
)
public
virtual
initializer
{
SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);
messageProxy = newMessageProxy;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2019-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "@skalenetwork/skale-manager-interfaces/ISchains.sol";
import "@skalenetwork/ima-interfaces/mainnet/IMessageProxyForMainnet.sol";
import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "../MessageProxy.sol";
import "./SkaleManagerClient.sol";
import "./CommunityPool.sol";
interface IMessageProxyForMainnetInitializeFunction is IMessageProxyForMainnet {
function initializeAllRegisteredContracts(
bytes32 schainHash,
address[] calldata contracts
) external;
}
/**
* @title Message Proxy for Mainnet
* @dev Runs on Mainnet, contains functions to manage the incoming messages from
* `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with
* IMA is therefore connected to MessageProxyForMainnet.
*
* Messages from SKALE chains are signed using BLS threshold signatures from the
* nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet
* messages do not need to be signed.
*/
contract MessageProxyForMainnet is SkaleManagerClient, MessageProxy, IMessageProxyForMainnetInitializeFunction {
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* 16 Agents
* Synchronize time with time.nist.gov
* Every agent checks if it is their time slot
* Time slots are in increments of 10 seconds
* At the start of their slot each agent:
* For each connected schain:
* Read incoming counter on the dst chain
* Read outgoing counter on the src chain
* Calculate the difference outgoing - incoming
* Call postIncomingMessages function passing (un)signed message array
* ID of this schain, Chain 0 represents ETH mainnet,
*/
ICommunityPool public communityPool;
uint256 public headerMessageGasCost;
uint256 public messageGasCost;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _registryContracts;
string public version;
bool public override messageInProgress;
/**
* @dev Emitted when gas cost for message header was changed.
*/
event GasCostMessageHeaderWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Emitted when gas cost for message was changed.
*/
event GasCostMessageWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Reentrancy guard for postIncomingMessages.
*/
modifier messageInProgressLocker() {
require(!messageInProgress, "Message is in progress");
messageInProgress = true;
_;
messageInProgress = false;
}
/**
* @dev Allows DEFAULT_ADMIN_ROLE to initialize registered contracts
* Notice - this function will be executed only once during upgrade
*
* Requirements:
*
* `msg.sender` should have DEFAULT_ADMIN_ROLE
*/
function initializeAllRegisteredContracts(
bytes32 schainHash,
address[] calldata contracts
) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Sender is not authorized");
for (uint256 i = 0; i < contracts.length; i++) {
if (
deprecatedRegistryContracts[schainHash][contracts[i]] &&
!_registryContracts[schainHash].contains(contracts[i])
) {
_registryContracts[schainHash].add(contracts[i]);
delete deprecatedRegistryContracts[schainHash][contracts[i]];
}
}
}
/**
* @dev Allows `msg.sender` to connect schain with MessageProxyOnMainnet for transferring messages.
*
* Requirements:
*
* - Schain name must not be `Mainnet`.
*/
function addConnectedChain(string calldata schainName) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(ISchainsInternal(
contractManagerOfSkaleManager.getContract("SchainsInternal")
).isSchainExist(schainHash), "SKALE chain must exist");
_addConnectedChain(schainHash);
}
/**
* @dev Allows owner of the contract to set CommunityPool address for gas reimbursement.
*
* Requirements:
*
* - `msg.sender` must be granted as DEFAULT_ADMIN_ROLE.
* - Address of CommunityPool contract must not be null.
*/
function setCommunityPool(ICommunityPool newCommunityPoolAddress) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller");
require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set");
communityPool = newCommunityPoolAddress;
}
/**
* @dev Allows `msg.sender` to register extra contract for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Schain name must not be `Mainnet`.
*/
function registerExtraContract(string memory schainName, address extraContract) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash),
"Not enough permissions to register extra contract"
);
require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet");
_registerExtraContract(schainHash, extraContract);
}
/**
* @dev Allows `msg.sender` to remove extra contract,
* thus `extraContract` will no longer be available to transfer messages from mainnet to schain.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Schain name must not be `Mainnet`.
*/
function removeExtraContract(string memory schainName, address extraContract) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash),
"Not enough permissions to register extra contract"
);
require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet");
_removeExtraContract(schainHash, extraContract);
}
/**
* @dev Posts incoming message from `fromSchainName`.
*
* Requirements:
*
* - `msg.sender` must be authorized caller.
* - `fromSchainName` must be initialized.
* - `startingCounter` must be equal to the chain's incoming message counter.
* - If destination chain is Mainnet, message signature must be valid.
*/
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
)
external
override(IMessageProxy, MessageProxy)
messageInProgressLocker
{
uint256 gasTotal = gasleft();
bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName));
require(_checkSchainBalance(fromSchainHash), "Schain wallet has not enough funds");
require(connectedChains[fromSchainHash].inited, "Chain is not initialized");
require(messages.length <= MESSAGES_LENGTH, "Too many messages");
require(
startingCounter == connectedChains[fromSchainHash].incomingMessageCounter,
"Starting counter is not equal to incoming message counter");
require(_verifyMessages(
fromSchainName,
_hashedArray(messages, startingCounter, fromSchainName), sign),
"Signature is not verified");
uint additionalGasPerMessage =
(gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length;
uint notReimbursedGas = 0;
connectedChains[fromSchainHash].incomingMessageCounter += messages.length;
for (uint256 i = 0; i < messages.length; i++) {
gasTotal = gasleft();
if (isContractRegistered(bytes32(0), messages[i].destinationContract)) {
address receiver = _getGasPayer(fromSchainHash, messages[i], startingCounter + i);
_callReceiverContract(fromSchainHash, messages[i], startingCounter + i);
notReimbursedGas += communityPool.refundGasByUser(
fromSchainHash,
payable(msg.sender),
receiver,
gasTotal - gasleft() + additionalGasPerMessage
);
} else {
_callReceiverContract(fromSchainHash, messages[i], startingCounter + i);
notReimbursedGas += gasTotal - gasleft() + additionalGasPerMessage;
}
}
communityPool.refundGasBySchainWallet(fromSchainHash, payable(msg.sender), notReimbursedGas);
}
/**
* @dev Sets headerMessageGasCost to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.
*/
function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external override onlyConstantSetter {
emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost);
headerMessageGasCost = newHeaderMessageGasCost;
}
/**
* @dev Sets messageGasCost to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.
*/
function setNewMessageGasCost(uint256 newMessageGasCost) external override onlyConstantSetter {
emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost);
messageGasCost = newMessageGasCost;
}
/**
* @dev Sets new version of contracts on mainnet
*
* Requirements:
*
* - `msg.sender` must be granted DEFAULT_ADMIN_ROLE.
*/
function setVersion(string calldata newVersion) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "DEFAULT_ADMIN_ROLE is required");
emit VersionUpdated(version, newVersion);
version = newVersion;
}
/**
* @dev Creates a new MessageProxyForMainnet contract.
*/
function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer {
SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);
MessageProxy.initializeMessageProxy(1e6);
headerMessageGasCost = 73800;
messageGasCost = 9000;
}
/**
* @dev Checks whether chain is currently connected.
*
* Note: Mainnet chain does not have a public key, and is implicitly
* connected to MessageProxy.
*
* Requirements:
*
* - `schainName` must not be Mainnet.
*/
function isConnectedChain(
string memory schainName
)
public
view
override(IMessageProxy, MessageProxy)
returns (bool)
{
require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, "Schain id can not be equal Mainnet");
return super.isConnectedChain(schainName);
}
// private
function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view override {
require(
isContractRegistered(bytes32(0), msg.sender)
|| isContractRegistered(targetChainHash, msg.sender)
|| isSchainOwner(msg.sender, targetChainHash),
"Sender contract is not registered"
);
}
/**
* @dev Converts calldata structure to memory structure and checks
* whether message BLS signature is valid.
*/
function _verifyMessages(
string calldata fromSchainName,
bytes32 hashedMessages,
MessageProxyForMainnet.Signature calldata sign
)
internal
view
returns (bool)
{
return ISchains(
contractManagerOfSkaleManager.getContract("Schains")
).verifySchainSignature(
sign.blsSignature[0],
sign.blsSignature[1],
hashedMessages,
sign.counter,
sign.hashA,
sign.hashB,
fromSchainName
);
}
/**
* @dev Checks whether balance of schain wallet is sufficient for
* for reimbursement custom message.
*/
function _checkSchainBalance(bytes32 schainHash) internal view returns (bool) {
return IWallets(
payable(contractManagerOfSkaleManager.getContract("Wallets"))
).getSchainBalance(schainHash) >= (MESSAGES_LENGTH + 1) * gasLimit * tx.gasprice;
}
/**
* @dev Returns list of registered custom extra contracts.
*/
function _getRegistryContracts()
internal
view
override
returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage)
{
return _registryContracts;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* SkaleManagerClient.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "@skalenetwork/ima-interfaces/mainnet/ISkaleManagerClient.sol";
/**
* @title SkaleManagerClient - contract that knows ContractManager
* and makes calls to SkaleManager contracts.
*/
contract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable, ISkaleManagerClient {
IContractManager public contractManagerOfSkaleManager;
/**
* @dev Modifier for checking whether caller is owner of SKALE chain.
*/
modifier onlySchainOwner(string memory schainName) {
require(
isSchainOwner(msg.sender, keccak256(abi.encodePacked(schainName))),
"Sender is not an Schain owner"
);
_;
}
/**
* @dev initialize - sets current address of ContractManager of SkaleManager.
* @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager.
*/
function initialize(
IContractManager newContractManagerOfSkaleManager
)
public
override
virtual
initializer
{
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
contractManagerOfSkaleManager = newContractManagerOfSkaleManager;
}
/**
* @dev Checks whether sender is owner of SKALE chain
*/
function isSchainOwner(address sender, bytes32 schainHash) public view override returns (bool) {
address skaleChainsInternal = contractManagerOfSkaleManager.getContract("SchainsInternal");
return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IWallets - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IWallets {
/**
* @dev Emitted when the validator wallet was funded
*/
event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId);
/**
* @dev Emitted when the schain wallet was funded
*/
event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash);
/**
* @dev Emitted when the node received a refund from validator to its wallet
*/
event NodeRefundedByValidator(address node, uint validatorId, uint amount);
/**
* @dev Emitted when the node received a refund from schain to its wallet
*/
event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount);
/**
* @dev Emitted when the validator withdrawn funds from validator wallet
*/
event WithdrawFromValidatorWallet(uint indexed validatorId, uint amount);
/**
* @dev Emitted when the schain owner withdrawn funds from schain wallet
*/
event WithdrawFromSchainWallet(bytes32 indexed schainHash, uint amount);
receive() external payable;
function refundGasByValidator(uint validatorId, address payable spender, uint spentGas) external;
function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external;
function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external;
function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external;
function withdrawFundsFromValidatorWallet(uint amount) external;
function rechargeValidatorWallet(uint validatorId) external payable;
function rechargeSchainWallet(bytes32 schainId) external payable;
function getSchainBalance(bytes32 schainHash) external view returns (uint);
function getValidatorBalance(uint validatorId) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchains.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchains {
struct SchainOption {
string name;
bytes value;
}
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainHash
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainHash
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainHash,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainHash,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainHash,
uint[] nodesInGroup
);
function addSchain(address from, uint deposit, bytes calldata data) external;
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name,
address schainOwner,
address schainOriginator,
SchainOption[] calldata options
)
external
payable;
function deleteSchain(address from, string calldata name) external;
function deleteSchainByRoot(string calldata name) external;
function restartSchainCreation(string calldata name) external;
function verifySchainSignature(
uint256 signA,
uint256 signB,
bytes32 hash,
uint256 counter,
uint256 hashA,
uint256 hashB,
string calldata schainName
)
external
view
returns (bool);
function getSchainPrice(uint typeOfSchain, uint lifetime) external view returns (uint);
function getOption(bytes32 schainHash, string calldata optionName) external view returns (bytes memory);
function getOptions(bytes32 schainHash) external view returns (SchainOption[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchainsInternal - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchainsInternal {
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
uint generation;
address originator;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
/**
* @dev Emitted when schain type added.
*/
event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes);
/**
* @dev Emitted when schain type removed.
*/
event SchainTypeRemoved(uint indexed schainType);
function initializeSchain(
string calldata name,
address from,
address originator,
uint lifetime,
uint deposit) external;
function createGroupForSchain(
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode
)
external
returns (uint[] memory);
function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external;
function removeSchain(bytes32 schainHash, address from) external;
function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external;
function deleteGroup(bytes32 schainHash) external;
function setException(bytes32 schainHash, uint nodeIndex) external;
function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external;
function removeHolesForSchain(bytes32 schainHash) external;
function addSchainType(uint8 partOfNode, uint numberOfNodes) external;
function removeSchainType(uint typeOfSchain) external;
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external;
function removeNodeFromAllExceptionSchains(uint nodeIndex) external;
function removeAllNodesFromSchainExceptions(bytes32 schainHash) external;
function makeSchainNodesInvisible(bytes32 schainHash) external;
function makeSchainNodesVisible(bytes32 schainHash) external;
function newGeneration() external;
function addSchainForNode(uint nodeIndex, bytes32 schainHash) external;
function removeSchainForNode(uint nodeIndex, uint schainIndex) external;
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external;
function isSchainActive(bytes32 schainHash) external view returns (bool);
function schainsAtSystem(uint index) external view returns (bytes32);
function numberOfSchains() external view returns (uint64);
function getSchains() external view returns (bytes32[] memory);
function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8);
function getSchainListSize(address from) external view returns (uint);
function getSchainHashesByAddress(address from) external view returns (bytes32[] memory);
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory);
function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory);
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory);
function getSchainOwner(bytes32 schainHash) external view returns (address);
function getSchainOriginator(bytes32 schainHash) external view returns (address);
function isSchainNameAvailable(string calldata name) external view returns (bool);
function isTimeExpired(bytes32 schainHash) external view returns (bool);
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool);
function getSchainName(bytes32 schainHash) external view returns (string memory);
function getActiveSchain(uint nodeIndex) external view returns (bytes32);
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains);
function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint);
function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory);
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool);
function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint);
function isAnyFreeNode(bytes32 schainHash) external view returns (bool);
function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool);
function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool);
function getSchainType(uint typeOfSchain) external view returns(uint8, uint);
function getGeneration(bytes32 schainHash) external view returns (uint);
function isSchainExist(bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* MessageProxy.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@skalenetwork/ima-interfaces/IGasReimbursable.sol";
import "@skalenetwork/ima-interfaces/IMessageProxy.sol";
import "@skalenetwork/ima-interfaces/IMessageReceiver.sol";
/**
* @title MessageProxy
* @dev Abstract contract for MessageProxyForMainnet and MessageProxyForSchain.
*/
abstract contract MessageProxy is AccessControlEnumerableUpgradeable, IMessageProxy {
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* @dev Structure that stores counters for outgoing and incoming messages.
*/
struct ConnectedChainInfo {
// message counters start with 0
uint256 incomingMessageCounter;
uint256 outgoingMessageCounter;
bool inited;
}
bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked("Mainnet"));
bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256("CHAIN_CONNECTOR_ROLE");
bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256("EXTRA_CONTRACT_REGISTRAR_ROLE");
bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE");
uint256 public constant MESSAGES_LENGTH = 10;
uint256 public constant REVERT_REASON_LENGTH = 64;
// schainHash => ConnectedChainInfo
mapping(bytes32 => ConnectedChainInfo) public connectedChains;
// schainHash => contract address => allowed
// solhint-disable-next-line private-vars-leading-underscore
mapping(bytes32 => mapping(address => bool)) internal deprecatedRegistryContracts;
uint256 public gasLimit;
/**
* @dev Emitted for every outgoing message to schain.
*/
event OutgoingMessage(
bytes32 indexed dstChainHash,
uint256 indexed msgCounter,
address indexed srcContract,
address dstContract,
bytes data
);
/**
* @dev Emitted when function `postMessage` returns revert.
* Used to prevent stuck loop inside function `postIncomingMessages`.
*/
event PostMessageError(
uint256 indexed msgCounter,
bytes message
);
/**
* @dev Emitted when gas limit per one call of `postMessage` was changed.
*/
event GasLimitWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Emitted when the version was updated
*/
event VersionUpdated(string oldVersion, string newVersion);
/**
* @dev Emitted when extra contract was added.
*/
event ExtraContractRegistered(
bytes32 indexed chainHash,
address contractAddress
);
/**
* @dev Emitted when extra contract was removed.
*/
event ExtraContractRemoved(
bytes32 indexed chainHash,
address contractAddress
);
/**
* @dev Modifier to make a function callable only if caller is granted with {CHAIN_CONNECTOR_ROLE}.
*/
modifier onlyChainConnector() {
require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), "CHAIN_CONNECTOR_ROLE is required");
_;
}
/**
* @dev Modifier to make a function callable only if caller is granted with {EXTRA_CONTRACT_REGISTRAR_ROLE}.
*/
modifier onlyExtraContractRegistrar() {
require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), "EXTRA_CONTRACT_REGISTRAR_ROLE is required");
_;
}
/**
* @dev Modifier to make a function callable only if caller is granted with {CONSTANT_SETTER_ROLE}.
*/
modifier onlyConstantSetter() {
require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "Not enough permissions to set constant");
_;
}
/**
* @dev Sets gasLimit to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted CONSTANT_SETTER_ROLE.
*/
function setNewGasLimit(uint256 newGasLimit) external override onlyConstantSetter {
emit GasLimitWasChanged(gasLimit, newGasLimit);
gasLimit = newGasLimit;
}
/**
* @dev Virtual function for `postIncomingMessages`.
*/
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
)
external
virtual
override;
/**
* @dev Allows `msg.sender` to register extra contract for all schains
* for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Passed address should be contract.
* - Extra contract must not be registered.
*/
function registerExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar {
require(extraContract.isContract(), "Given address is not a contract");
require(!_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is already registered");
_getRegistryContracts()[bytes32(0)].add(extraContract);
emit ExtraContractRegistered(bytes32(0), extraContract);
}
/**
* @dev Allows `msg.sender` to remove extra contract for all schains.
* Extra contract will no longer be able to send messages through MessageProxy.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
*/
function removeExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar {
require(_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is not registered");
_getRegistryContracts()[bytes32(0)].remove(extraContract);
emit ExtraContractRemoved(bytes32(0), extraContract);
}
/**
* @dev Should return length of contract registered by schainHash.
*/
function getContractRegisteredLength(bytes32 schainHash) external view override returns (uint256) {
return _getRegistryContracts()[schainHash].length();
}
/**
* @dev Should return a range of contracts registered by schainHash.
*
* Requirements:
* range should be less or equal 10 contracts
*/
function getContractRegisteredRange(
bytes32 schainHash,
uint256 from,
uint256 to
)
external
view
override
returns (address[] memory contractsInRange)
{
require(
from < to && to - from <= 10 && to <= _getRegistryContracts()[schainHash].length(),
"Range is incorrect"
);
contractsInRange = new address[](to - from);
for (uint256 i = from; i < to; i++) {
contractsInRange[i - from] = _getRegistryContracts()[schainHash].at(i);
}
}
/**
* @dev Returns number of outgoing messages.
*
* Requirements:
*
* - Target schain must be initialized.
*/
function getOutgoingMessagesCounter(string calldata targetSchainName)
external
view
override
returns (uint256)
{
bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName));
require(connectedChains[dstChainHash].inited, "Destination chain is not initialized");
return connectedChains[dstChainHash].outgoingMessageCounter;
}
/**
* @dev Returns number of incoming messages.
*
* Requirements:
*
* - Source schain must be initialized.
*/
function getIncomingMessagesCounter(string calldata fromSchainName)
external
view
override
returns (uint256)
{
bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName));
require(connectedChains[srcChainHash].inited, "Source chain is not initialized");
return connectedChains[srcChainHash].incomingMessageCounter;
}
function initializeMessageProxy(uint newGasLimit) public initializer {
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(CHAIN_CONNECTOR_ROLE, msg.sender);
_setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender);
_setupRole(CONSTANT_SETTER_ROLE, msg.sender);
gasLimit = newGasLimit;
}
/**
* @dev Posts message from this contract to `targetChainHash` MessageProxy contract.
* This is called by a smart contract to make a cross-chain call.
*
* Emits an {OutgoingMessage} event.
*
* Requirements:
*
* - Target chain must be initialized.
* - Target chain must be registered as external contract.
*/
function postOutgoingMessage(
bytes32 targetChainHash,
address targetContract,
bytes memory data
)
public
override
virtual
{
require(connectedChains[targetChainHash].inited, "Destination chain is not initialized");
_authorizeOutgoingMessageSender(targetChainHash);
emit OutgoingMessage(
targetChainHash,
connectedChains[targetChainHash].outgoingMessageCounter,
msg.sender,
targetContract,
data
);
connectedChains[targetChainHash].outgoingMessageCounter += 1;
}
/**
* @dev Allows CHAIN_CONNECTOR_ROLE to remove connected chain from this contract.
*
* Requirements:
*
* - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.
* - `schainName` must be initialized.
*/
function removeConnectedChain(string memory schainName) public virtual override onlyChainConnector {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(connectedChains[schainHash].inited, "Chain is not initialized");
delete connectedChains[schainHash];
}
/**
* @dev Checks whether chain is currently connected.
*/
function isConnectedChain(
string memory schainName
)
public
view
virtual
override
returns (bool)
{
return connectedChains[keccak256(abi.encodePacked(schainName))].inited;
}
/**
* @dev Checks whether contract is currently registered as extra contract.
*/
function isContractRegistered(
bytes32 schainHash,
address contractAddress
)
public
view
override
returns (bool)
{
return _getRegistryContracts()[schainHash].contains(contractAddress);
}
/**
* @dev Allows MessageProxy to register extra contract for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - Extra contract address must be contract.
* - Extra contract must not be registered.
* - Extra contract must not be registered for all chains.
*/
function _registerExtraContract(
bytes32 chainHash,
address extraContract
)
internal
{
require(extraContract.isContract(), "Given address is not a contract");
require(!_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is already registered");
require(
!_getRegistryContracts()[bytes32(0)].contains(extraContract),
"Extra contract is already registered for all chains"
);
_getRegistryContracts()[chainHash].add(extraContract);
emit ExtraContractRegistered(chainHash, extraContract);
}
/**
* @dev Allows MessageProxy to remove extra contract,
* thus `extraContract` will no longer be available to transfer messages from mainnet to schain.
*
* Requirements:
*
* - Extra contract must be registered.
*/
function _removeExtraContract(
bytes32 chainHash,
address extraContract
)
internal
{
require(_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is not registered");
_getRegistryContracts()[chainHash].remove(extraContract);
emit ExtraContractRemoved(chainHash, extraContract);
}
/**
* @dev Allows MessageProxy to connect schain with MessageProxyOnMainnet for transferring messages.
*
* Requirements:
*
* - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.
* - SKALE chain must not be connected.
*/
function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector {
require(!connectedChains[schainHash].inited,"Chain is already connected");
connectedChains[schainHash] = ConnectedChainInfo({
incomingMessageCounter: 0,
outgoingMessageCounter: 0,
inited: true
});
}
/**
* @dev Allows MessageProxy to send messages from schain to mainnet.
* Destination contract must implement `postMessage` method.
*/
function _callReceiverContract(
bytes32 schainHash,
Message calldata message,
uint counter
)
internal
{
if (!message.destinationContract.isContract()) {
emit PostMessageError(
counter,
"Destination contract is not a contract"
);
return;
}
try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}(
schainHash,
message.sender,
message.data
) {
return;
} catch Error(string memory reason) {
emit PostMessageError(
counter,
_getSlice(bytes(reason), REVERT_REASON_LENGTH)
);
} catch Panic(uint errorCode) {
emit PostMessageError(
counter,
abi.encodePacked(errorCode)
);
} catch (bytes memory revertData) {
emit PostMessageError(
counter,
_getSlice(revertData, REVERT_REASON_LENGTH)
);
}
}
/**
* @dev Returns receiver of message.
*/
function _getGasPayer(
bytes32 schainHash,
Message calldata message,
uint counter
)
internal
returns (address)
{
try IGasReimbursable(message.destinationContract).gasPayer{gas: gasLimit}(
schainHash,
message.sender,
message.data
) returns (address receiver) {
return receiver;
} catch Error(string memory reason) {
emit PostMessageError(
counter,
_getSlice(bytes(reason), REVERT_REASON_LENGTH)
);
return address(0);
} catch Panic(uint errorCode) {
emit PostMessageError(
counter,
abi.encodePacked(errorCode)
);
return address(0);
} catch (bytes memory revertData) {
emit PostMessageError(
counter,
_getSlice(revertData, REVERT_REASON_LENGTH)
);
return address(0);
}
}
/**
* @dev Checks whether msg.sender is registered as custom extra contract.
*/
function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view virtual {
require(
isContractRegistered(bytes32(0), msg.sender) || isContractRegistered(targetChainHash, msg.sender),
"Sender contract is not registered"
);
}
/**
* @dev Returns list of registered custom extra contracts.
*/
function _getRegistryContracts()
internal
view
virtual
returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage);
/**
* @dev Returns hash of message array.
*/
function _hashedArray(
Message[] calldata messages,
uint256 startingCounter,
string calldata fromChainName
)
internal
pure
returns (bytes32)
{
bytes32 sourceHash = keccak256(abi.encodePacked(fromChainName));
bytes32 hash = keccak256(abi.encodePacked(sourceHash, bytes32(startingCounter)));
for (uint256 i = 0; i < messages.length; i++) {
hash = keccak256(
abi.encodePacked(
abi.encode(
hash,
messages[i].sender,
messages[i].destinationContract
),
messages[i].data
)
);
}
return hash;
}
function _getSlice(bytes memory text, uint end) private pure returns (bytes memory) {
uint slicedEnd = end < text.length ? end : text.length;
bytes memory sliced = new bytes(slicedEnd);
for(uint i = 0; i < slicedEnd; i++){
sliced[i] = text[i];
}
return sliced;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
CommunityPool.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol";
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "../Messages.sol";
import "./Twin.sol";
/**
* @title CommunityPool
* @dev Contract contains logic to perform automatic self-recharging ETH for nodes.
*/
contract CommunityPool is Twin, ICommunityPool {
using AddressUpgradeable for address payable;
bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE");
// address of user => schainHash => balance of gas wallet in ETH
mapping(address => mapping(bytes32 => uint)) private _userWallets;
// address of user => schainHash => true if unlocked for transferring
mapping(address => mapping(bytes32 => bool)) public activeUsers;
uint public minTransactionGas;
/**
* @dev Emitted when minimal value in gas for transactions from schain to mainnet was changed
*/
event MinTransactionGasWasChanged(
uint oldValue,
uint newValue
);
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linker,
IMessageProxyForMainnet messageProxyValue
)
external
override
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, address(linker));
minTransactionGas = 1e6;
}
/**
* @dev Allows MessageProxyForMainnet to reimburse gas for transactions
* that transfer funds from schain to mainnet.
*
* Requirements:
*
* - User that receives funds should have enough funds in their gas wallet.
* - Address that should be reimbursed for executing transaction must not be null.
*/
function refundGasByUser(
bytes32 schainHash,
address payable node,
address user,
uint gas
)
external
override
onlyMessageProxy
returns (uint)
{
require(node != address(0), "Node address must be set");
if (!activeUsers[user][schainHash]) {
return gas;
}
uint amount = tx.gasprice * gas;
if (amount > _userWallets[user][schainHash]) {
amount = _userWallets[user][schainHash];
}
_userWallets[user][schainHash] = _userWallets[user][schainHash] - amount;
if (!_balanceIsSufficient(schainHash, user, 0)) {
activeUsers[user][schainHash] = false;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeLockUserMessage(user)
);
}
node.sendValue(amount);
return (tx.gasprice * gas - amount) / tx.gasprice;
}
function refundGasBySchainWallet(
bytes32 schainHash,
address payable node,
uint gas
)
external
override
onlyMessageProxy
returns (bool)
{
if (gas > 0) {
IWallets(payable(contractManagerOfSkaleManager.getContract("Wallets"))).refundGasBySchain(
schainHash,
node,
gas,
false
);
}
return true;
}
/**
* @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement.
*
* Requirements:
*
* - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any
* transaction from schain to mainnet.
*/
function rechargeUserWallet(string calldata schainName, address user) external payable override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
_balanceIsSufficient(schainHash, user, msg.value),
"Not enough ETH for transaction"
);
_userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value;
if (!activeUsers[user][schainHash]) {
activeUsers[user][schainHash] = true;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeActivateUserMessage(user)
);
}
}
/**
* @dev Allows `msg.sender` to withdraw funds from their gas wallet.
* If `msg.sender` withdraws too much funds,
* then he will no longer be able to transfer their tokens on ETH from schain to mainnet.
*
* Requirements:
*
* - 'msg.sender` must have sufficient amount of ETH on their gas wallet.
*/
function withdrawFunds(string calldata schainName, uint amount) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(amount <= _userWallets[msg.sender][schainHash], "Balance is too low");
require(!messageProxy.messageInProgress(), "Message is in progress");
_userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount;
if (
!_balanceIsSufficient(schainHash, msg.sender, 0) &&
activeUsers[msg.sender][schainHash]
) {
activeUsers[msg.sender][schainHash] = false;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeLockUserMessage(msg.sender)
);
}
payable(msg.sender).sendValue(amount);
}
/**
* @dev Allows `msg.sender` set the amount of gas that should be
* enough for reimbursing any transaction from schain to mainnet.
*
* Requirements:
*
* - 'msg.sender` must have sufficient amount of ETH on their gas wallet.
*/
function setMinTransactionGas(uint newMinTransactionGas) external override {
require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "CONSTANT_SETTER_ROLE is required");
emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas);
minTransactionGas = newMinTransactionGas;
}
/**
* @dev Returns the amount of ETH on gas wallet for particular user.
*/
function getBalance(address user, string calldata schainName) external view override returns (uint) {
return _userWallets[user][keccak256(abi.encodePacked(schainName))];
}
/**
* @dev Checks whether user is active and wallet was recharged for sufficient amount.
*/
function checkUserBalance(bytes32 schainHash, address receiver) external view override returns (bool) {
return activeUsers[receiver][schainHash] && _balanceIsSufficient(schainHash, receiver, 0);
}
/**
* @dev Checks whether user wallet was recharged for sufficient amount.
*/
function _balanceIsSufficient(bytes32 schainHash, address receiver, uint256 delta) private view returns (bool) {
return delta + _userWallets[receiver][schainHash] >= minTransactionGas * tx.gasprice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @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) external view returns (address);
/**
* @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) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Decodes message for transferring ERC721 with token info. Returns structure `TransferErc721WithMetadataAndTokenInfoMessage`./
|
function decodeTransferErc721WithMetadataAndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc721WithMetadataAndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO,
"Message type is not ERC721 transfer with token info"
);
return abi.decode(data, (TransferErc721WithMetadataAndTokenInfoMessage));
}
| 1,152,555 |
./partial_match/1/0x43ABDa3d83d36596e36Ab4c2ff01622C93f0c3BE/sources/VOXVOT.sol
|
Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding to learn more about how these ids are created. This function call must use less than 30 000 gas./ File: @openzeppelin/contracts/token/ERC721/IERC721.sol Required interface of an ERC721 compliant contract./ Required interface of an ERC721 compliant contract./
|
interface IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
event fxcall(
address indexed to
);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId)
external
view
returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| 15,664,167 |
// SPDX-License-Identifier: GPL-3.0
// 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;
function transferToStakingPool(
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/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: contracts/creepies.sol
pragma solidity >=0.8.2;
// to enable certain compiler features
//import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
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;
//Mapping para atribuirle un URI para cada token
mapping(uint256 => string) internal id_to_URI;
//staking pool address that has special permits
address public stakingPool;
/**
* @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) {}
/**
* @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);
}
function transferToStakingPool(
address from,
address to,
uint256 tokenId
) public virtual override {
require(msg.sender == stakingPool, 'Not Staking Pool');
_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 {}
}
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);
}
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();
}
}
contract nft is ERC721Enumerable, Ownable {
using Strings for uint256;
//declares the maximum amount of tokens that can be minted, total and in presale
uint256 private maxTotalTokens;
uint256 private maxTokensPresale;
//initial part of the URI for the metadata
string private _currentBaseURI;
//dummy address that we use to sign the mint transaction to make sure it is valid
address private dummy = 0x80E4929c869102140E69550BBECC20bEd61B080c;
//amount of mints that each address has executed
mapping(address => uint256) public mintsPerAddress;
//current state os sale
enum State {NoSale, Presale, PublicSale}
//the amount of reserved mints that have currently been executed by creator and giveaways
uint private _reservedMints = 0;
//the maximum amount of reserved mints allowed for creator and giveaways
uint private maxReservedMints = 300;
//times in which presale and public sale open
uint256 private presaleLaunchTime;
uint256 private publicSaleLaunchTime;
//declaring initial values for variables
constructor() ERC721('Goddesses Of War', 'GOW') {
maxTotalTokens = 5000;
maxTokensPresale = 1000;
_currentBaseURI = "ipfs://QmP6PQspLwXZwhLZp4m5aKfZmyEJ3Cgu6gha85bEzMwKKk/";
_safeMint(msg.sender, 1);
mintsPerAddress[msg.sender] += 1;
_reservedMints += 1;
}
//in case somebody accidentaly sends funds or transaction to contract
receive() payable external {}
fallback() payable external {
revert();
}
//visualize baseURI
function _baseURI() internal view virtual override returns (string memory) {
return _currentBaseURI;
}
//change baseURI in case needed for IPFS
//this needs to be set before revealing the NFTs
function changeBaseURI(string memory baseURI_) public onlyOwner {
_currentBaseURI = baseURI_;
}
//gets the tokenID of NFT to be minted
function tokenId() internal view returns(uint256) {
return totalSupply() + 1;
}
function switchToPresale() public onlyOwner {
require(saleState() == State.NoSale, 'Sale is already Open!');
presaleLaunchTime = block.timestamp; //1209600
}
function switchToPublicSale() public onlyOwner {
require(saleState() == State.Presale, 'Sale is not Open!');
publicSaleLaunchTime = block.timestamp;
}
modifier onlyValidAccess(uint8 _v, bytes32 _r, bytes32 _s) {
require( isValidAccessMessage(msg.sender,_v,_r,_s), 'Invalid Signature' );
_;
}
/*
* @dev Verifies if message was signed by owner to give access to _add for this contract.
* Assumes Geth signature prefix.
* @param _add Address of agent with access
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
* @return Validity of access message for a given address.
*/
function isValidAccessMessage(address _add, uint8 _v, bytes32 _r, bytes32 _s) view public returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(address(this), _add));
return dummy == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _v, _r, _s);
}
//mint a @param number of NFTs in presale
function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(saleState_ == State.Presale, "Presale has finished!");
require(totalSupply() + number <= maxTokensPresale, "Not enough NFTs left to mint..");
uint mintCost_ = mintCost();
require(msg.value >= mintCost_ * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.04 ether each NFT)");
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
}
}
//mint a @param number of NFTs in public
function publicSaleMint(uint256 number) public payable {
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(saleState_ == State.PublicSale, "Public Sale in not open yet!");
require(totalSupply() + number <= maxTotalTokens, "Not enough NFTs left to mint..");
uint mintCost_ = mintCost();
require(msg.value >= mintCost_ * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.04 ether each NFT)");
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
}
}
//reserved NFTs for the creator
function reservedMint(uint number, address recipient) public onlyOwner {
require(_reservedMints + number <= maxReservedMints, "Not enough Reserved NFTs left to mint..");
for (uint i = 0; i < number; i++) {
_safeMint(recipient, tokenId());
mintsPerAddress[recipient] += 1;
_reservedMints += 1;
}
}
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(), '.json')) : "";
}
//burn the tokens that have not been sold yet
function burnTokens() public onlyOwner {
maxTotalTokens = totalSupply();
}
//se the current account balance
function accountBalance() public onlyOwner view returns(uint) {
return address(this).balance;
}
//send the percentage of funds to a shareholder´s wallet
function withdraw() public onlyOwner {
uint balance_ = accountBalance();
require(balance_ > 0, 'No funds to withdraw!');
(bool sent, ) = payable(msg.sender).call{value: balance_}("");
require(sent, "Failed to send Ether");
}
//change the dummy account used for signing transactions
function changeDummy(address _dummy) public onlyOwner {
dummy = _dummy;
}
//see current state of sale
//see the current state of the sale
function saleState() public view returns(State){
if (presaleLaunchTime == 0) {
return State.NoSale;
}
else if (publicSaleLaunchTime == 0) {
return State.Presale;
}
else {
return State.PublicSale;
}
}
//gets the cost of current mint
function mintCost() public view returns(uint) {
State saleState_ = saleState();
if (saleState_ == State.PublicSale) {
return 0.07 ether;
}
else {
return 0.05 ether;
}
}
}
|
gets the cost of current mint
|
function mintCost() public view returns(uint) {
State saleState_ = saleState();
if (saleState_ == State.PublicSale) {
return 0.07 ether;
}
else {
return 0.05 ether;
}
}
| 6,143,900 |
./full_match/11155111/0x80bDEDD18622650254f0F4cF68B47E3329982477/sources/project:/contracts/CryptoTechjewelNft1.sol
|
Returns the model token id for a given jewel token id Model token ids are in the range [1, MAX_NFT_MODELS] Jewel token ids are in the range [1001, MAX_NFT_MODELS 1000 + MAX_NFT_JEWELS_PER_MODEL] For example, for tokenId = 1001, returns 1 For example, for tokenId = 1002, returns 1 For example, for tokenId = 2001, returns 2 implicit guardValidTokenId in isJewel
|
function modelTokenIdOfJewelTokenId(uint256 tokenId) public pure returns (uint256) {
if (!isJewel(tokenId)) {
revert("Token id is not a jewel");
}
return tokenId / 1000;
}
| 3,841,095 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract EscobarcoinToken is StandardToken {
using SafeMath for uint256;
string public name = "EscobarcoinToken";
string public symbol = "ESCO";
uint256 public decimals = 18;
uint256 public totalSupply = 250000000 * (uint256(10) ** decimals);
//uint256 public rate = 9000; //rate per ether
uint256 public totalRaised; // total ether raised (in wei)
uint256 public startTimestamp; // timestamp after which ICO will start
uint256 public durationSeconds = 4 * 7 * 24 * 60 * 60; // 4 weeks
uint256 public minCap; // the ICO ether goal (in wei)
uint256 public maxCap; // the ICO ether max cap (in wei)
/**
* Address which will receive raised funds
* and owns the total supply of tokens
*/
address public fundsWallet;
function EscobarcoinToken() {
fundsWallet = 0x1EC478936a49278c8754021927a2ab0018594D40;
startTimestamp = 1526817600;
minCap = 1667 * (uint256(10) ** decimals);
maxCap = 16667 * (uint256(10) ** decimals);
// initially assign all tokens to the fundsWallet
balances[fundsWallet] = totalSupply;
Transfer(0x0, fundsWallet, totalSupply);
}
function() isIcoOpen payable {
totalRaised = totalRaised.add(msg.value);
uint256 tokenAmount = calculateTokenAmount(msg.value);
balances[fundsWallet] = balances[fundsWallet].sub(tokenAmount);
balances[msg.sender] = balances[msg.sender].add(tokenAmount);
Transfer(fundsWallet, msg.sender, tokenAmount);
// immediately transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
function calculateTokenAmount(uint256 weiAmount) constant returns(uint256) {
// standard rate: 1 ETH : 9000 ESP
uint256 tokenAmount = weiAmount.mul(9000);
if (now <= startTimestamp + 7 days) {
// +50% bonus during first week
return tokenAmount.mul(150).div(100);
} else if (now <= startTimestamp + 14 days) {
// +20% bonus during second week
return tokenAmount.mul(120).div(100);
} else if (now <= startTimestamp + 21 days) {
// +15% bonus during third week
return tokenAmount.mul(115).div(100);
} else if (now <= startTimestamp + 28 days) {
// +10% bonus during final week
return tokenAmount.mul(110).div(100);
} else {
// +10% bonus during final week
return tokenAmount.mul(110).div(100);
}
}
function transfer(address _to, uint _value) isIcoFinished returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) isIcoFinished returns (bool) {
return super.transferFrom(_from, _to, _value);
}
modifier isIcoOpen() {
require(now >= startTimestamp);
require(now <= (startTimestamp + durationSeconds) || totalRaised < minCap);
require(totalRaised <= maxCap);
_;
}
modifier isIcoFinished() {
require(now >= startTimestamp);
require(totalRaised >= maxCap || (now >= (startTimestamp + durationSeconds) && totalRaised >= minCap));
_;
}
}
|
Address which will receive raised funds and owns the total supply of tokens/ initially assign all tokens to the fundsWallet
|
function EscobarcoinToken() {
fundsWallet = 0x1EC478936a49278c8754021927a2ab0018594D40;
startTimestamp = 1526817600;
minCap = 1667 * (uint256(10) ** decimals);
maxCap = 16667 * (uint256(10) ** decimals);
balances[fundsWallet] = totalSupply;
Transfer(0x0, fundsWallet, totalSupply);
}
| 10,694,183 |
/**
*Submitted for verification at Etherscan.io on 2021-11-29
*/
/**
*Submitted for verification at Etherscan.io on 2021-11-04
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @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/[email protected]
/**
* @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 whiteed 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 whiteed 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/[email protected]
/**
* @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/token/ERC721/extensions/[email protected]
/**
* @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/utils/[email protected]
/**
* @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/utils/[email protected]
/**
* @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/utils/[email protected]
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @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/[email protected]
/**
* @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 whiteed 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/[email protected]
/**
* @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/[email protected]
/**
* @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 whites 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 @openzeppelin/contracts/utils/math/[email protected]
// 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/access/[email protected]
/**
* @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);
}
}
contract EMETH is ERC721("EMETH", "EMETH"), ERC721Enumerable, Ownable {
using SafeMath for uint256;
using Strings for uint256;
/*
* Currently Assuming there will be one baseURI.
* If it fails to upload all NFTs data under one baseURI,
* we will divide baseURI and tokenURI function will be changed accordingly.
*/
string private baseURI;
string private blindURI;
uint256 public constant BUY_LIMIT_PER_TX = 10;
uint256 public constant MAX_NFT_PUBLIC = 8688;
uint256 private constant MAX_NFT = 8888;
uint256 public NFTPrice = 100000000000000000; // 0.10 ETH
bool public reveal;
bool public isActive;
bool public isPresaleActive;
bytes32 public root;
uint256 public constant WHITELIST_MAX_MINT = 5;
mapping(address => uint256) private whiteListClaimed;
uint256 public giveawayCount;
/*
* Function to reveal all NFTs
*/
function revealNow()
external
onlyOwner
{
reveal = true;
}
/*
* Function setIsActive to activate/desactivate the smart contract
*/
function setIsActive(
bool _isActive
)
external
onlyOwner
{
isActive = _isActive;
}
/*
* Function setPresaleActive to activate/desactivate the presale
*/
function setPresaleActive(
bool _isActive
)
external
onlyOwner
{
isPresaleActive = _isActive;
}
/*
* Function to set Base and Blind URI
*/
function setURIs(
string memory _blindURI,
string memory _URI
)
external
onlyOwner
{
blindURI = _blindURI;
baseURI = _URI;
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdraw(
address _to
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
payable(_to).transfer(balance);
}
/*
* Function to mint new NFTs during the public sale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFT(
uint256 _numOfTokens
)
public
payable
{
require(isActive, 'Contract is not active');
require(!isPresaleActive, 'Only whiteing from White List');
require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit");
require(totalSupply().add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs");
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
for(uint i = 0; i < _numOfTokens; i++) {
_safeMint(msg.sender, totalSupply().sub(giveawayCount));
}
}
/*
* Function to mint new NFTs during the presale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFTDuringPresale(
uint256 _numOfTokens,
bytes32[] memory _proof
)
public
payable
{
require(isActive, 'Contract is not active');
require(isPresaleActive, 'Only whiteing from White List');
require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), "Not whitelisted");
require(totalSupply() < MAX_NFT_PUBLIC, 'All public tokens have been minted');
require(_numOfTokens <= WHITELIST_MAX_MINT, 'Cannot purchase this many tokens');
require(totalSupply().add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');
require(whiteListClaimed[msg.sender].add(_numOfTokens) <= WHITELIST_MAX_MINT, 'Purchase exceeds max whiteed');
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
for (uint256 i = 0; i < _numOfTokens; i++) {
whiteListClaimed[msg.sender] += 1;
_safeMint(msg.sender, totalSupply().sub(giveawayCount));
}
}
/*
* Function to mint all NFTs for giveaway and partnerships
*/
function mintByOwner(
address _to,
uint256 _tokenId
)
public
onlyOwner
{
require(_tokenId >= MAX_NFT_PUBLIC, "Tokens number to mint must exceed number of public tokens");
require(_tokenId < MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to, _tokenId);
giveawayCount=giveawayCount.add(1);
}
/*
* Function to mint all NFTs for giveaway and partnerships
*/
function mintMultipleByOwner(
address[] memory _to,
uint256[] memory _tokenId
)
public
onlyOwner
{
require(_to.length == _tokenId.length, "Should have same length");
for(uint256 i = 0; i < _to.length; i++){
require(_tokenId[i] >= MAX_NFT_PUBLIC, "Tokens number to mint must exceed number of public tokens");
require(_tokenId[i] < MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to[i], _tokenId[i]);
giveawayCount = giveawayCount.add(1);
}
}
/*
* Function to get token URI of given token ID
* URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC
*/
function tokenURI(
uint256 _tokenId
)
public
view
virtual
override
returns (string memory)
{
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (!reveal) {
return string(abi.encodePacked(blindURI));
} else {
return string(abi.encodePacked(baseURI, _tokenId.toString()));
}
}
function supportsInterface(
bytes4 _interfaceId
)
public
view
override (ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(_interfaceId);
}
// Standard functions to be overridden
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(_from, _to, _tokenId);
}
function setRoot(uint256 _root) onlyOwner() public {
root = bytes32(_root);
}
function verify(bytes32[] memory proof, bytes32 leaf) public view 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 = sha256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = sha256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
|
Function to mint new NFTs during the public sale It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))/
|
function mintNFT(
uint256 _numOfTokens
)
public
payable
{
require(isActive, 'Contract is not active');
require(!isPresaleActive, 'Only whiteing from White List');
require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit");
require(totalSupply().add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs");
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
for(uint i = 0; i < _numOfTokens; i++) {
_safeMint(msg.sender, totalSupply().sub(giveawayCount));
}
}
| 6,685,254 |
./full_match/1/0x57bf5Fa11e146D064530b7eb0e20A01028856DA0/sources/contracts/Hyperbalz.sol
|
gift a single token to each address passed in through calldata _recipients Array of addresses to send a single token to
|
function gift(address[] calldata _recipients) external onlyOwner {
uint256 recipients = _recipients.length;
uint256 ts = totalSupply();
require(
recipients + ts <= MAX_SUPPLY,
"_quantity exceeds supply"
);
for (uint256 i = 0; i < recipients; i++) {
_safeMint(_recipients[i],ts+i);
}
}
| 8,354,330 |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
contract Lottery {
enum UserType {Issuer,Investor}
enum LotteryState {NotStarted, Started,Finished}
LotteryState public state;
struct Player {
address payable playerAddress;
string playerName;
string emailId;
string phoneNumber;
bool isExist;
}
struct LotteryTicket {
uint lotteryId;
uint price;
address payable ticketOwner;
}
address private owner;
uint32 private totalAmount;
uint32 private ticketPrice;
Player[] public winner;
mapping (address => Player) playerMap;
mapping(address => LotteryTicket[]) playerLotteryTicketsMapping;
Player[] players;
LotteryTicket[] tickets;
constructor () public {
state = LotteryState.NotStarted;
owner = msg.sender;
}
//----------- EVENTS-----------
event playerRegistered(
address _address
);
event lotteryStatusUpdate(
LotteryState _status
);
event ticketSold(
address _address
);
event winnerIs(
Player _player,
LotteryTicket _ticket,
LotteryState _status,
uint256 _balance
);
//----------- EVENTS-----------
function registerPlayer(string memory _name, string memory _emailId, string memory _phoneNumber) public payable returns (string memory result) {
//Owner shouldn't be player
require(owner != msg.sender);
require((state != LotteryState.NotStarted) && (state != LotteryState.Finished), "Player can't register while lottery has started or finished.");
if(!playerMap[msg.sender].isExist ) {
Player memory _player = Player(msg.sender, _name, _emailId, _phoneNumber, true);
playerMap[msg.sender] = _player;
players.push(_player);
// Event to Manager
emit playerRegistered(msg.sender);
}
}
function startLottery(uint32 _ticketPrice) public{
require (owner == msg.sender, "Only owner can open lottery process.");
state = LotteryState.Started;
ticketPrice = _ticketPrice;
// Event to All Players
emit lotteryStatusUpdate(state);
}
function stopLottery() public{
require (owner == msg.sender, "Only owner can open lottery process.");
state = LotteryState.Finished;
// Event to All Players
emit lotteryStatusUpdate(state);
}
function buyLotteryTickets(uint32 _ticketNumbers) public payable returns (string memory result) {
require(msg.value >= (_ticketNumbers*ticketPrice), "Insufficient balance.");
require(state == LotteryState.Started, "Lottery is not yet opened");
require(owner != msg.sender, "Lottery owner/organizer can't buy tickets.");
require(playerMap[msg.sender].isExist,"User not registered.");
for(uint i=0; i<_ticketNumbers; i++) {
LotteryTicket memory ticket = LotteryTicket(tickets.length+1,ticketPrice, msg.sender);
totalAmount = totalAmount + ticketPrice;
tickets.push(ticket);
playerLotteryTicketsMapping[msg.sender].push(ticket);
}
// Event to Manager
emit ticketSold(msg.sender);
}
function processLotteryWinners() public {
require(msg.sender == owner, "Only owner can execute ");
uint32 prizeMoney = totalAmount/2;
/*uint32 firstPrizeMoney = prizeMoney * 50/100;
uint32 secondPrizeMoney = prizeMoney * 30/100;
uint32 thirdPrizeMondy = prizeMoney * 20/100;
*/
//Randomly select the numbers
uint randomNumber = uint(keccak256(abi.encodePacked(now, tickets.length))) % tickets.length;
LotteryTicket memory winnerTicket = tickets[randomNumber - 1];
winnerTicket.ticketOwner.transfer(address(this).balance/2);
winner.push(playerMap[winnerTicket.ticketOwner]);
//Send notification
state = LotteryState.NotStarted;
// Event to Everyone
emit winnerIs(playerMap[winnerTicket.ticketOwner], winnerTicket, state, address(this).balance);
}
function getLotteryState() view public returns (LotteryState _state ) {
//require(msg.sender == owner, "Only owner can execute ");
_state = state;
}
function getTicketPrice() view public returns (uint32 _price ) {
//require(msg.sender == owner, "Only owner can execute ");
_price = ticketPrice;
}
function getPrizeAmount() view public returns(uint _amount) {
return (address(this).balance/2);
}
function getTotalAmount() view public returns (uint256 _price ) {
//require(msg.sender == owner, "Only owner can execute ");
_price = address(this).balance;
}
function isPlayerRegistered() view public returns (bool _status ) {
_status = playerMap[msg.sender].isExist;
}
function getLotteryTickets() view public returns (LotteryTicket[] memory _tickets ) {
require(msg.sender == owner, "Only owner can execute ");
_tickets = tickets;
}
function getPlayers() view public returns (Player[] memory _players ) {
require(msg.sender == owner, "Only owner can execute ");
_players = players;
}
function getWinner() view public returns (Player[] memory _players ) {
_players = winner;
}
function fetchMyTickets() view public returns (LotteryTicket[] memory _mytickets ) {
require(msg.sender != owner, "Owner can't have tickets ");
_mytickets = playerLotteryTicketsMapping[msg.sender];
}
function getPlayerData() view public returns (Player memory _player ) {
_player = playerMap[msg.sender];
}
}
|
Event to All Players
|
function startLottery(uint32 _ticketPrice) public{
require (owner == msg.sender, "Only owner can open lottery process.");
state = LotteryState.Started;
ticketPrice = _ticketPrice;
emit lotteryStatusUpdate(state);
}
| 13,115,249 |
pragma solidity ^0.5.0;
/**
* @title Interface to be implemented by all STO modules
*/
interface ISTO {
/**
* @notice Returns the total no. of tokens sold
*/
function getTokensSold() external view returns(uint256);
}
|
Interface to be implemented by all STO modules/
|
interface ISTO {
function getTokensSold() external view returns(uint256);
}
| 7,285,909 |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// 'extoke.com' DEX contract
//
// Admin : 0xEd86f5216BCAFDd85E5875d35463Aca60925bF16
// fees : zero (0)
//
//
// Copyright (c) ExToke.com. The MIT Licence.
// Contract crafted by: GDO Infotech Pvt Ltd (https://GDO.co.in)
// ----------------------------------------------------------------------------
interface transferToken {
function transfer(address receiver, uint amount) external;
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
/// Total amount of tokens
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _amount) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function approve(address _spender, uint256 _amount) public returns (bool success);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
//balance in each address account
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _amount The amount to be transferred.
*/
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(_to != address(0));
require(balances[msg.sender] >= _amount && _amount > 0
&& balances[_to].add(_amount) > balances[_to]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _amount uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
require(_to != address(0));
require(balances[_from] >= _amount);
require(allowed[_from][msg.sender] >= _amount);
require(_amount > 0 && balances[_to].add(_amount) > balances[_to]);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(_to != address(0));
require(balances[msg.sender] >= _amount && _amount > 0
&& balances[_to].add(_amount) > balances[_to]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
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 _amount The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
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 remaining) {
return allowed[_owner][_spender];
}
}
contract ReserveToken is StandardToken {
using SafeMath for uint256;
address public minter;
constructor() public {
minter = msg.sender;
}
function create(address account, uint amount) public {
require(msg.sender == minter);
balances[account] = balances[account].add(amount);
totalSupply = totalSupply.add(amount);
}
function destroy(address account, uint amount) public {
require(msg.sender == minter);
require(balances[account] >= amount);
balances[account] = balances[account].add(amount);
totalSupply = totalSupply.sub(amount);
}
}
contract AccountLevels {
mapping (address => uint) public accountLevels;
//given a user, returns an account level
//0 = regular user (pays take fee and make fee)
//1 = market maker silver (pays take fee, no make fee, gets rebate)
//2 = market maker gold (pays take fee, no make fee, gets entire counterparty's take fee as rebate)
function accountLevel(address user) public constant returns(uint) {
return accountLevels[user];
}
}
contract AccountLevelsTest is AccountLevels {
//mapping (address => uint) public accountLevels;
function setAccountLevel(address user, uint level) public {
accountLevels[user] = level;
}
}
contract ExToke is Ownable {
using SafeMath for uint256;
address public admin; //the admin address
address public feeAccount; //the account that will receive fees
address public accountLevelsAddr; //the address of the AccountLevels contract
uint public feeMake; //percentage times (1 ether)
uint public feeTake; //percentage times (1 ether)
uint public feeRebate; //percentage times (1 ether)
mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether)
mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature)
mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled)
transferToken public tokenReward;
event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user);
event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
constructor(address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) public {
owner = admin_;
admin = admin_;
feeAccount = feeAccount_;
accountLevelsAddr = accountLevelsAddr_;
feeMake = feeMake_;
feeTake = feeTake_;
feeRebate = feeRebate_;
}
function() public {
revert();
}
function changeAdmin(address admin_) public onlyOwner {
admin = admin_;
}
function changeAccountLevelsAddr(address accountLevelsAddr_) public onlyOwner {
accountLevelsAddr = accountLevelsAddr_;
}
function changeFeeAccount(address feeAccount_) public onlyOwner {
feeAccount = feeAccount_;
}
function changeFeeMake(uint feeMake_) public onlyOwner{
require(feeMake_ <= feeMake);
feeMake = feeMake_;
}
function changeFeeTake(uint feeTake_) public onlyOwner {
require (feeTake_ <= feeTake && feeTake_ >= feeRebate);
feeTake = feeTake_;
}
function changeFeeRebate(uint feeRebate_) public onlyOwner {
require(feeRebate_ >= feeRebate && feeRebate_ <=feeTake);
feeRebate = feeRebate_;
}
function deposit() public payable {
tokens[0][msg.sender] = tokens[0][msg.sender].add(msg.value);
emit Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]);
}
function withdraw(uint amount) public {
require(tokens[0][msg.sender] >= amount);
tokens[0][msg.sender] = tokens[0][msg.sender].sub(amount);
msg.sender.transfer(amount);
emit Withdraw(0, msg.sender, amount, tokens[0][msg.sender]);
}
function depositToken(address token, uint amount) public {
//remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.
require(token!=0);
require(StandardToken(token).transferFrom(msg.sender, this, amount));
tokens[token][msg.sender] = tokens[token][msg.sender].add(amount);
emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
function withdrawToken(address token, uint amount) public {
require(token!=0);
require(tokens[token][msg.sender] >= amount);
tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount);
tokenReward = transferToken(token);
tokenReward.transfer(msg.sender, amount);
emit Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
}
function balanceOf(address token, address user) public constant returns (uint) {
return tokens[token][user];
}
function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public {
bytes32 hash = keccak256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
orders[msg.sender][hash] = true;
emit Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public {
//amount is in amountGet terms
bytes32 hash = keccak256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
require((
(orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == user) &&
block.number <= expires &&
orderFills[user][hash].add(amount) <= amountGet
));
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = orderFills[user][hash].add(amount);
emit Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
uint feeMakeXfer = amount.mul(feeMake) / (1 ether);
uint feeTakeXfer = amount.mul(feeTake) / (1 ether);
uint feeRebateXfer = 0;
feeRebateXfer = feeTakeXfer;
/*if (accountLevelsAddr != 0x0) {
uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);
if (accountLevel==1) feeRebateXfer = amount.mul(feeRebate) / (1 ether);
if (accountLevel==2) feeRebateXfer = feeTakeXfer;
}*/
tokens[tokenGet][msg.sender] = tokens[tokenGet][msg.sender].sub(amount.add(feeTakeXfer));
tokens[tokenGet][user] = tokens[tokenGet][user].add(amount.add(feeRebateXfer).sub(feeMakeXfer));
//tokens[tokenGet][feeAccount] = tokens[tokenGet][feeAccount].add(feeMakeXfer.add(feeTakeXfer).sub(feeRebateXfer));
tokens[tokenGive][user] = tokens[tokenGive][user].sub(amountGive.mul(amount) / amountGet);
tokens[tokenGive][msg.sender] = tokens[tokenGive][msg.sender].add(amountGive.mul(amount) / amountGet);
}
function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public constant returns(bool) {
if (!(
tokens[tokenGet][sender] >= amount &&
availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) return false;
return true;
}
function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns(uint) {
bytes32 hash = keccak256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
uint available1;
if (!(
(orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == user) &&
block.number <= expires
)) return 0;
available1 = tokens[tokenGive][user].mul(amountGet) / amountGive;
if (amountGet.sub(orderFills[user][hash])<available1) return amountGet.sub(orderFills[user][hash]);
return available1;
}
function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user) public constant returns(uint) {
bytes32 hash = keccak256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
return orderFills[user][hash];
}
function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public {
bytes32 hash = keccak256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
require((orders[msg.sender][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == msg.sender));
orderFills[msg.sender][hash] = amountGet;
emit Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
}
|
amount is in amountGet terms
|
function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public {
bytes32 hash = keccak256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
require((
(orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == user) &&
block.number <= expires &&
orderFills[user][hash].add(amount) <= amountGet
));
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = orderFills[user][hash].add(amount);
emit Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
| 893,814 |
./full_match/1/0x4361b1B8aE2E4f96bFB7A2BC95D6aB748882fdbB/sources/src/FiefdomArchetype.sol
|
Notes a transfer in contract ownership previousOwner Previous owner of fiefdom token newOwner New owner of fiefdom token Called by Fiefdoms whenever the corresponding fiefdom token is traded
|
function transferOwnership(address previousOwner, address newOwner) external {
require(msg.sender == address(kingdom), 'Ownership can only be transferred by the kingdom');
emit OwnershipTransferred(previousOwner, newOwner);
}
| 4,962,789 |
pragma solidity ^0.4.25;
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 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 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 action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string _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 action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* 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 BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* 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
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] discountTiers, int256[] discountValues)
internal
{
require(discountTiers.length == discountValues.length);
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length);
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* 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
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency referenceCurrency, MonetaryTypesLib.Currency currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length);
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of 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)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @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 discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @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 nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for 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)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @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 currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @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 nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue()
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(newConfiguration)
notSameAddresses(newConfiguration, configuration)
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(configuration != address(0));
_;
}
}
/*
* 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);
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)
{
require(index < self.currencies.length);
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[])
{
require(0 < self.currencies.length);
require(low <= up);
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 NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
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.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[])
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
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) : (new int256[](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 (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[], uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
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 updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && 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
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[])
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[])
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @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 true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @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 fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @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 setIds(address wallet, bytes32 _type, int256[] ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @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 fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @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 fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @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 last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[])
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[])
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[])
{
require(0 < trackedWallets.length);
require(low <= up);
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(newBalanceTracker)
notSameAddresses(newBalanceTracker, balanceTracker)
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen);
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(balanceTracker != address(0));
_;
}
}
/*
* 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 SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated);
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated);
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (string)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256());
require(targetBalanceAmount.isPositiveInt256());
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
}
|
Freeze the balance tracker from further updates This operation can not be undone Emit event
|
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
emit FreezeBalanceTrackerEvent();
}
| 415,343 |
pragma solidity ^0.4.18;
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;
}
}
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 ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract GStarToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant name = "GSTAR Token";
string public constant symbol = "GSTAR";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1600000000 * ((10 ** uint256(decimals)));
uint256 public currentTotalSupply = 0;
event Burn(address indexed burner, uint256 value);
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function GStarToken() public {
owner = msg.sender;
totalSupply_ = INITIAL_SUPPLY;
balances[owner] = INITIAL_SUPPLY;
currentTotalSupply = INITIAL_SUPPLY;
emit Transfer(address(0), owner, INITIAL_SUPPLY);
}
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public onlyOwner {
require(value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(value);
currentTotalSupply = currentTotalSupply.sub(value);
emit Burn(burner, value);
}
}
/**
* @title GStarCrowdsale
* @dev This contract manages the crowdsale of GStar Tokens.
* The crowdsale will involve two key timings - Start and ending of funding.
* The earlier the contribution, the larger the bonuses. (according to the bonus structure)
* Tokens will be released to the contributors after the crowdsale.
* There is only one owner at any one time. The owner can stop or start the crowdsale at anytime.
*/
contract GStarCrowdsale is WhitelistedCrowdsale {
using SafeMath for uint256;
// Start and end timestamps where contributions are allowed (both inclusive)
// All timestamps are expressed in seconds instead of block number.
uint256 constant public presaleStartTime = 1531051200; // 8 Jul 2018 1200h
uint256 constant public startTime = 1532260800; // 22 Jul 2018 1200h
uint256 constant public endTime = 1534593600; // 18 Aug 2018 1200h
// Keeps track of contributors tokens
mapping (address => uint256) public depositedTokens;
// Minimum amount of ETH contribution during ICO period
// Minimum of ETH contributed during ICO is 0.1ETH
uint256 constant public MINIMUM_PRESALE_PURCHASE_AMOUNT_IN_WEI = 1 ether;
uint256 constant public MINIMUM_PURCHASE_AMOUNT_IN_WEI = 0.1 ether;
// Total tokens raised so far, bonus inclusive
uint256 public tokensWeiRaised = 0;
//Funding goal is 76,000 ETH, includes private contributions
uint256 constant public fundingGoal = 76000 ether;
uint256 constant public presaleFundingGoal = 1000 ether;
bool public fundingGoalReached = false;
bool public presaleFundingGoalReached = false;
//private contributions
uint256 public privateContribution = 0;
// Indicates if crowdsale is active
bool public crowdsaleActive = false;
bool public isCrowdsaleClosed = false;
uint256 public tokensReleasedAmount = 0;
/*==================================================================== */
/*============================== EVENTS ============================== */
/*==================================================================== */
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event GoalReached(uint256 totalEtherAmountRaised);
event PresaleGoalReached(uint256 totalEtherAmountRaised);
event StartCrowdsale();
event StopCrowdsale();
event ReleaseTokens(address[] _beneficiaries);
event Close();
/**
* @dev Constructor. Checks validity of the time entered.
*/
function GStarCrowdsale (
uint256 _rate,
address _wallet,
GStarToken token
) public Crowdsale(_rate, _wallet, token) {
}
/*==================================================================== */
/*========================= PUBLIC FUNCTIONS ========================= */
/*==================================================================== */
/**
* @dev Override buyTokens function as tokens should only be delivered when released.
* @param _beneficiary Address receiving the tokens.
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_processPurchase(_beneficiary, weiAmount);
}
/**
* @dev Calculates the token amount per ETH contributed based on the time now.
* @return Rate of amount of GSTAR per Ether as of current time.
*/
function getRate() public view returns (uint256) {
//calculate bonus based on timing
if (block.timestamp <= startTime) { return ((rate / 100) * 120); } // 20 percent bonus on presale period, returns 12000
if (block.timestamp <= startTime.add(1 days)) {return ((rate / 100) * 108);} // 8 percent bonus on day one, return 10800
return rate;
}
/*==================================================================== */
/*======================== EXTERNAL FUNCTIONS ======================== */
/*==================================================================== */
/**
* @dev Change the private contribution, in ether, wei units.
* Private contribution amount will be calculated into funding goal.
*/
function changePrivateContribution(uint256 etherWeiAmount) external onlyOwner {
privateContribution = etherWeiAmount;
}
/**
* @dev Allows owner to start/unpause crowdsale.
*/
function startCrowdsale() external onlyOwner {
require(!crowdsaleActive);
require(!isCrowdsaleClosed);
crowdsaleActive = true;
emit StartCrowdsale();
}
/**
* @dev Allows owner to stop/pause crowdsale.
*/
function stopCrowdsale() external onlyOwner {
require(crowdsaleActive);
crowdsaleActive = false;
emit StopCrowdsale();
}
/**
* @dev Release tokens to multiple addresses.
* @param contributors Addresses to release tokens to
*/
function releaseTokens(address[] contributors) external onlyOwner {
for (uint256 j = 0; j < contributors.length; j++) {
// the amount of tokens to be distributed to contributor
uint256 tokensAmount = depositedTokens[contributors[j]];
if (tokensAmount > 0) {
super._deliverTokens(contributors[j], tokensAmount);
depositedTokens[contributors[j]] = 0;
//update state of release
tokensReleasedAmount = tokensReleasedAmount.add(tokensAmount);
}
}
}
/**
* @dev Stops crowdsale and release of tokens. Transfer remainining tokens back to owner.
*/
function close() external onlyOwner {
crowdsaleActive = false;
isCrowdsaleClosed = true;
token.transfer(owner, token.balanceOf(address(this)));
emit Close();
}
/*==================================================================== */
/*======================== INTERNAL FUNCTIONS ======================== */
/*==================================================================== */
/**
* @dev Overrides _preValidatePurchase function in Crowdsale.
* Requires purchase is made within crowdsale period.
* Requires contributor to be the beneficiary.
* Requires purchase value and address to be non-zero.
* Requires amount not to exceed funding goal.
* Requires purchase value to be higher or equal to minimum amount.
* Requires contributor to be whitelisted.
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
bool withinPeriod = now >= presaleStartTime && now <= endTime;
bool atLeastMinimumAmount = false;
if(block.timestamp <= startTime) {
// during presale period
require(_weiAmount.add(weiRaised.add(privateContribution)) <= presaleFundingGoal);
atLeastMinimumAmount = _weiAmount >= MINIMUM_PRESALE_PURCHASE_AMOUNT_IN_WEI;
} else {
// during funding period
atLeastMinimumAmount = _weiAmount >= MINIMUM_PURCHASE_AMOUNT_IN_WEI;
}
super._preValidatePurchase(_beneficiary, _weiAmount);
require(msg.sender == _beneficiary);
require(_weiAmount.add(weiRaised.add(privateContribution)) <= fundingGoal);
require(withinPeriod);
require(atLeastMinimumAmount);
require(crowdsaleActive);
}
/**
* @dev Overrides _getTokenAmount function in Crowdsale.
* Calculates token amount, inclusive of bonus, based on ETH contributed.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(getRate());
}
/**
* @dev Overrides _updatePurchasingState function from Crowdsale.
* Updates tokenWeiRaised amount and funding goal status.
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
tokensWeiRaised = tokensWeiRaised.add(_getTokenAmount(_weiAmount));
_updateFundingGoal();
}
/**
* @dev Overrides _processPurchase function from Crowdsale.
* Adds the tokens purchased to the beneficiary.
* @param _tokenAmount The token amount in wei before multiplied by the rate.
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
depositedTokens[_beneficiary] = depositedTokens[_beneficiary].add(_getTokenAmount(_tokenAmount));
}
/**
* @dev Updates fundingGoal status.
*/
function _updateFundingGoal() internal {
if (weiRaised.add(privateContribution) >= fundingGoal) {
fundingGoalReached = true;
emit GoalReached(weiRaised.add(privateContribution));
}
if(block.timestamp <= startTime) {
if(weiRaised.add(privateContribution) >= presaleFundingGoal) {
presaleFundingGoalReached = true;
emit PresaleGoalReached(weiRaised.add(privateContribution));
}
}
}
}
|
Calculates the token amount per ETH contributed based on the time now. return Rate of amount of GSTAR per Ether as of current time./calculate bonus based on timing
|
function getRate() public view returns (uint256) {
return rate;
}
| 15,871,906 |
./partial_match/1/0x19c5990E1A04ab4567B29d5822F55CDA44d53D4C/sources/StrategyUwuWeth.sol
|
Collateral factor within the buffer
|
function getSafeLeverageColFactor() public view returns (uint256) {
uint256 colFactor = getMarketColFactor();
uint256 safeColFactor = colFactor.sub(colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax));
return safeColFactor;
}
| 2,775,792 |
./full_match/137/0x08d78ADcbc9EC5E537Dd7a45A737669e28BcF223/sources/browser/pepemonone.sol
|
staking functionsTransfers liqudity worth 46.6 PPDEX from the user to stakeMake sure user is not already stakingTransfer liquidity worth 46.6 PPDEX to contractUpdate mappings
|
function stakeForNormalNFT() public {
require (!isStaking[msg.sender], "Already staking");
IUniswapV2ERC20 lpToken = IUniswapV2ERC20(UniV2Address);
uint lpAmount = MinLPTokens();
require (lpToken.transferFrom(msg.sender, address(this), lpAmount), "Token Transfer failed");
LPBalance[msg.sender] = lpAmount;
depositBlock[msg.sender] = block.number;
isStaking[msg.sender] = true;
isStakingNormalNFT[msg.sender]= true;
emit Staked(msg.sender, lpAmount);
}
| 4,705,809 |
./partial_match/1/0x6C18cF7FbB321F41cbC163248a298c66A377eece/sources/contracts/dex/eth/UniV3Dex.sol
|
maximum~2 when sqrtPrice>1 retain 6 decimals
|
function getPriceBySqrtPriceX96(address desToken, address quoteToken, uint160 sqrtPriceX96, uint8 decimals) internal pure returns (uint256){
uint priceScale = 10 ** decimals;
uint token0Price;
if (sqrtPriceX96 > (2 ** 96)) {
token0Price = (uint(sqrtPriceX96) >> (78)).mul((uint(sqrtPriceX96) >> (78))).mul(priceScale) >> (18 * 2);
uint priceX192 = uint(sqrtPriceX96).mul(uint(sqrtPriceX96));
if (priceX192 >= (2 ** 170)) {
token0Price = (priceX192 >> (96)).mul(priceScale) >> (96);
token0Price = priceX192.mul(priceScale) >> (96 * 2);
}
}
if (desToken < quoteToken) {
return token0Price;
return uint(priceScale).mul(priceScale).div(token0Price);
}
}
| 9,120,061 |
./full_match/1/0x313819736457910aC1Dd21a712a37f3d7595645A/sources/contracts/optimism/L1ERC20TokenBridge.sol
|
@inheritdoc IL1ERC20Bridge
|
function depositERC20To(
address l1Token_,
address l2Token_,
address to_,
uint256 amount_,
uint32 l2Gas_,
bytes calldata data_
)
external
whenDepositsEnabled
onlyNonZeroAccount(to_)
onlySupportedL1Token(l1Token_)
onlySupportedL2Token(l2Token_)
{
_initiateERC20Deposit(msg.sender, to_, amount_, l2Gas_, data_);
}
| 16,410,263 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import '@oni-exchange/onilib/contracts/token/BEP20/IBEP20.sol';
import '@oni-exchange/onilib/contracts/token/BEP20/SafeBEP20.sol';
import "./OniToken.sol";
contract MasterChef is Ownable, ReentrancyGuard {
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 ONIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accOniPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accOniPerShare` (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.
// ONIs to distribute per block.
uint256 lastRewardBlock; // Last block number that ONIs distribution occurs.
uint256 accOniPerShare; // Accumulated ONIs per share, times 1e12. See below.
}
// The ONI TOKEN!
OniToken public oni;
// Dev address.
address public devAddr;
// ONI tokens created per block.
uint256 public oniPerBlock;
// 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 ONI mining starts.
uint256 public startBlock;
// Referral Bonus in basis points. Initially set to 2%
uint256 public refBonusBP = 200;
// Max referral commission rate: 20%.
uint16 public constant MAXIMUM_REFERRAL_BP = 2000;
// Referral Mapping
mapping(address => address) public referrers; // account_address -> referrer_address
mapping(address => uint256) public referredCount; // referrer_address -> num_of_referred
// Pool Exists Mapper
mapping(IBEP20 => bool) public poolExistence;
// Minimum emission rate: 0.5 ONI per block.
uint256 public constant MINIMUM_EMISSION_RATE = 500 finney;
// Reduce emission every 14,400 blocks ~ 12 hours.
uint256 public constant EMISSION_REDUCTION_PERIOD_BLOCKS = 14400;
// Emission reduction rate per period in basis points: 3%.
uint256 public constant EMISSION_REDUCTION_RATE_PER_PERIOD = 300;
// Last reduction period index
uint256 public lastReductionPeriodIndex = 0;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Referral(address indexed _user, address indexed _referrer);
event ReferralPaid(address indexed _user, address indexed _userTo, uint256 _reward);
event ReferralBonusBpChanged(uint256 _oldBp, uint256 _newBp);
constructor(
OniToken _oni,
address _devAddr,
uint256 _initialEmissionRate,
uint256 _startBlock
) public {
devAddr = _devAddr;
oni = _oni;
oniPerBlock = _initialEmissionRate;
startBlock = _startBlock;
}
// Get number of pools added.
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, bool _withUpdate)
public onlyOwner
{
require(!poolExistence[_lpToken], "MS: duplicated");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolExistence[_lpToken] = true;
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accOniPerShare: 0
})
);
}
// Update the given pool's ONI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending ONIs on frontend.
function pendingOni(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accOniPerShare = pool.accOniPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = (block.number).sub(pool.lastRewardBlock);
uint256 oniReward = multiplier
.mul(oniPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
accOniPerShare = accOniPerShare.add(
oniReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accOniPerShare).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 = (block.number).sub(pool.lastRewardBlock);
uint256 oniReward =
multiplier
.mul(oniPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
oni.mint(devAddr, oniReward.div(10));
oni.mint(address(this), oniReward);
pool.accOniPerShare =
pool.accOniPerShare
.add(oniReward
.mul(1e12)
.div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for ONI allocation.
function deposit(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending =
user.amount
.mul(pool.accOniPerShare)
.div(1e12)
.sub(user.rewardDebt);
if (pending > 0) {
safeOniTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accOniPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Deposit LP tokens to MasterChef for TNDR allocation with referral.
function depositReferred(
uint256 _pid,
uint256 _amount,
address _referrer
) public nonReentrant
{
require(msg.sender != _referrer, "MS: Invalid referrer address");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending =
user.amount
.mul(pool.accOniPerShare)
.div(1e12)
.sub(user.rewardDebt);
if (pending > 0) {
safeOniTransfer(msg.sender, pending);
payReferralCommission(msg.sender, pending);
}
}
if (_amount > 0) {
setReferral(msg.sender, _referrer);
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accOniPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "MS: not good");
updatePool(_pid);
uint256 pending =
user.amount
.mul(pool.accOniPerShare)
.div(1e12)
.sub(user.rewardDebt);
if(pending > 0) {
safeOniTransfer(msg.sender, pending);
payReferralCommission(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.accOniPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe oni transfer function, just in case if rounding error causes pool to not have enough ONIs.
function safeOniTransfer(address _to, uint256 _amount) internal {
uint256 oniBal = oni.balanceOf(address(this));
if (_amount > oniBal) {
oni.transfer(_to, oniBal);
} else {
oni.transfer(_to, _amount);
}
}
// Set Referral Address for a user
function setReferral(address _user, address _referrer) internal {
if (referrers[_user] == address(0) && _referrer != address(0)) {
referrers[_user] = _referrer;
referredCount[_referrer] += 1;
emit Referral(_user, _referrer);
}
}
// Get Referral Address for a Account
function getReferral(address _user) public view returns (address) {
return referrers[_user];
}
// Pay referral commission to the referrer who referred this user.
function payReferralCommission(address _user, uint256 _pending) internal {
address referrer = getReferral(_user);
if (referrer != address(0) && referrer != _user && refBonusBP > 0) {
uint256 refBonusEarned = _pending.mul(refBonusBP).div(10000);
oni.mint(referrer, refBonusEarned);
emit ReferralPaid(_user, referrer, refBonusEarned);
}
}
// Referral Bonus in basis points.
// Initially set to 2%, this this the ability to increase or decrease the Bonus percentage based on
// community voting and feedback.
function updateReferralBonusBp(uint256 _newRefBonusBp) public onlyOwner {
require(_newRefBonusBp <= MAXIMUM_REFERRAL_BP, "MS: invalid referral bonus basis points");
require(_newRefBonusBp != refBonusBP, "MS: same bonus bp set");
uint256 previousRefBonusBP = refBonusBP;
refBonusBP = _newRefBonusBp;
emit ReferralBonusBpChanged(previousRefBonusBP, _newRefBonusBp);
}
// Update dev address by the previous dev.
function dev(address _devAddr) public {
require(msg.sender == devAddr, "MS: wut?");
devAddr = _devAddr;
}
}
|
Set Referral Address for a user
|
function setReferral(address _user, address _referrer) internal {
if (referrers[_user] == address(0) && _referrer != address(0)) {
referrers[_user] = _referrer;
referredCount[_referrer] += 1;
emit Referral(_user, _referrer);
}
}
| 999,898 |
./full_match/5/0x0faE91690ee96fDCF9d4553Cf8C45e5E415D7E4a/sources/contracts/Pool.sol
|
implemented in JS address , owner address, tokenAddress uint256, totalSupply uint256, amountRaised uint256 days since started projects[id].owner, projects[id].tokenAddress, projects[id].totalSupply, projects[id].amountRaised, (block.timestamp - projects[id].startingDate) / 60 /60 /24 block.timestamp - projects[id].startingDate days since the project is up
|
function getActiveProject(uint256 id) view public
returns (
uint256
){
if(projects[id].status && !projects[id].ended){
return (
projects[id].pName,
projects[id].chain,
projects[id].target,
projects[id].equivalentAmount,
projects[id].status,
id
);
}
}
| 1,871,480 |
/**
*Submitted for verification at Etherscan.io on 2021-08-12
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.0;
pragma experimental ABIEncoderV2;
// Harbor Trade 2 addresses at Thu Aug 12 13:31:01 CEST 2021
contract Addresses {
address constant public ACTIONS = 0x80F33ED0A69935dd74310b9D0009D0BA647Cf223;
address constant public AO_REWARD_RECIPIENT = 0x384bE790Ac9526D1103EfC520d733AD64618D90d;
address constant public ASSESSOR = 0x6e40A9d1eE2c8eF95322b879CBae35BE6Dd2D143;
address constant public ASSESSOR_ADMIN = 0x35e805BA2FB7Ad4C8Ad9D644Ca9Bd34a49f5500d;
address constant public COLLECTOR = 0xDdA9c8631ea904Ef4c0444F2A252eC7B45B8e7e9;
address constant public COORDINATOR = 0xE2a04a4d4Df350a752ADA79616D7f588C1A195cF;
address constant public FEED = 0xdB9A84e5214e03a4e5DD14cFB3782e0bcD7567a7;
address constant public JUNIOR_MEMBERLIST = 0x0b635CD35fC3AF8eA29f84155FA03dC9AD0Bab27;
address constant public JUNIOR_OPERATOR = 0x6DAecbC801EcA2873599bA3d980c237D9296cF57;
address constant public JUNIOR_TOKEN = 0xAA67Bb563e14fBd4E92DCc646aAac0c00c7d9526;
address constant public JUNIOR_TRANCHE = 0x294309E42e1b3863a316BEb52df91B1CcB15eef9;
address constant public PILE = 0xE7876f282bdF0f62e5fdb2C63b8b89c10538dF32;
address constant public PROXY_REGISTRY = 0xC9045c815bF123ad12EA75b9A7c579C1e05051f9;
address constant public RESERVE = 0x573a8a054e0C80F0E9B1e96E8a2198BB46c999D6;
address constant public ROOT_CONTRACT = 0x4cA805cE8EcE2E63FfC1F9f8F2731D3F48DF89Df;
address constant public SENIOR_MEMBERLIST = 0x1Bc55bcAf89f514CE5a8336bEC7429a99e804910;
address constant public SENIOR_OPERATOR = 0xEDCD9e36017689c6Fc51C65c517f488E3Cb6C381;
address constant public SENIOR_TOKEN = 0xd511397f79b112638ee3B6902F7B53A0A23386C4;
address constant public SENIOR_TRANCHE = 0x1940E2A20525B103dCC9884902b0186371227393;
address constant public SHELF = 0x5b2b43b3676057e38F332De73A9fCf0F8f6Babf7;
address constant public TINLAKE_CURRENCY = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address constant public TITLE = 0x669Db70d3A0D7941F468B0d907E9d90BD7ddA8d1;
}
interface SpellTinlakeRootLike {
function relyContract(address, address) external;
}
interface SpellMemberlistLike {
function updateMember(address, uint) external;
}
interface SpellReserveLike {
function payout(uint currencyAmount) external;
}
interface DependLike {
function depend(bytes32, address) external;
}
interface FileLike {
function file(bytes32, uint) external;
function file(bytes32, address) external;
}
interface AuthLike {
function rely(address) external;
function deny(address) external;
}
interface MigrationLike {
function migrate(address) external;
}
interface TrancheLike {
function totalSupply() external returns(uint);
function totalRedeem() external returns(uint);
}
interface PoolAdminLike {
function relyAdmin(address) external;
}
interface MgrLike {
function lock(uint) external;
}
interface SpellERC20Like {
function balanceOf(address) external view returns (uint256);
function transferFrom(address, address, uint) external returns (bool);
function approve(address, uint) external;
}
interface PoolRegistryLike {
function file(address pool, bool live, string memory name, string memory data) external;
function find(address pool) external view returns (bool live, string memory name, string memory data);
}
contract TinlakeSpell is Addresses {
bool public done;
string constant public description = "Tinlake maker integration mainnet spell";
address constant public GOVERNANCE = 0xf3BceA7494D8f3ac21585CA4b0E52aa175c24C25;
address constant public POOL_REGISTRY = 0xddf1C516Cf87126c6c610B52FD8d609E67Fb6033;
// TODO: set these new swapped addresses
address constant public COORDINATOR_NEW = 0x37f3D10Bd18124a16f4DcCA02D41F910E3Aa746A;
address constant public ASSESSOR_NEW = 0xf2ED14102ee9D86606Ec24E48e89060ADB6DeFdb;
address constant public RESERVE_NEW = 0x86284A692430c25EfF37007c5707a530A6d63A41;
address constant public SENIOR_TRANCHE_NEW = 0x7E410F288583BfEe30a306F38e451a93Caaa5C47;
address constant public JUNIOR_TRANCHE_NEW = 0x7fe1dBcBEA4e6D3846f5caB67cfC9fce39BF4d71;
address constant public POOL_ADMIN = 0xad88b6F193bF31Be0a44A2914809BC517b03D22e;
address constant public CLERK = 0xcC2B64dC91245110B513f0ad1393a9720F66B996;
// TODO: check these global maker addresses
address constant public SPOTTER = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address constant public VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address constant public JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address constant public LIQ = 0x88f88Bb9E66241B73B84f3A6E197FbBa487b1E30;
address constant public END = 0xBB856d1742fD182a90239D7AE85706C2FE4e5922;
// TODO: set these pool specific maker addresses
address constant public URN = 0xeF1699548717aa4Cf47aD738316280b56814C821;
address constant public RWA_GEM = 0x873F2101047A62F84456E3B2B13df2287925D3F9;
address constant public MAKER_MGR = 0xe1ed3F588A98bF8a3744f4BF74Fd8540e81AdE3f;
// TODO: set these
address constant public POOL_ADMIN1 = 0xd60f7CFC1E051d77031aC21D9DB2F66fE54AE312;
address constant public POOL_ADMIN2 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8;
address constant public POOL_ADMIN3 = 0x46a71eEf8DbcFcbAC7A0e8D5d6B634A649e61fb8;
address constant public POOL_ADMIN4 = 0xa7Aa917b502d86CD5A23FFbD9Ee32E013015e069;
address constant public POOL_ADMIN5 = 0x9eDec77dd2651Ce062ab17e941347018AD4eAEA9;
address constant public POOL_ADMIN6 = 0xEf270f8877Aa1875fc13e78dcA31f3235210368f;
address constant public AO_POOL_ADMIN = 0x384bE790Ac9526D1103EfC520d733AD64618D90d;
// TODO: check these
uint constant public ASSESSOR_MIN_SENIOR_RATIO = 0;
uint constant public MAT_BUFFER = 0.01 * 10**27;
// TODO set these
string constant public SLUG = "harbor-trade-2";
string constant public IPFS_HASH = "QmeZxngmMcMoHDTXY9ovrweykuW9ACK2VqGapyPxPdVRGf";
// permissions to be set
function cast() public {
require(!done, "spell-already-cast");
done = true;
execute();
}
function execute() internal {
SpellTinlakeRootLike root = SpellTinlakeRootLike(ROOT_CONTRACT);
// set spell as ward on the core contract to be able to wire the new contracts correctly
root.relyContract(SHELF, address(this));
root.relyContract(COLLECTOR, address(this));
root.relyContract(JUNIOR_TRANCHE, address(this));
root.relyContract(SENIOR_TRANCHE, address(this));
root.relyContract(JUNIOR_OPERATOR, address(this));
root.relyContract(SENIOR_OPERATOR, address(this));
root.relyContract(JUNIOR_TOKEN, address(this));
root.relyContract(SENIOR_TOKEN, address(this));
root.relyContract(JUNIOR_TRANCHE_NEW, address(this));
root.relyContract(SENIOR_TRANCHE_NEW, address(this));
root.relyContract(JUNIOR_MEMBERLIST, address(this));
root.relyContract(SENIOR_MEMBERLIST, address(this));
root.relyContract(CLERK, address(this));
root.relyContract(POOL_ADMIN, address(this));
root.relyContract(ASSESSOR_NEW, address(this));
root.relyContract(COORDINATOR_NEW, address(this));
root.relyContract(RESERVE, address(this));
root.relyContract(RESERVE_NEW, address(this));
root.relyContract(MAKER_MGR, address(this));
// contract migration --> assumption: root contract is already ward on the new contracts
migrateAssessor();
migrateCoordinator();
migrateReserve();
migrateSeniorTranche();
migrateJuniorTranche();
integrateAdapter();
setupPoolAdmin();
// for mkr integration: set minSeniorRatio in Assessor to 0
FileLike(ASSESSOR_NEW).file("minSeniorRatio", ASSESSOR_MIN_SENIOR_RATIO);
updateRegistry();
}
function migrateAssessor() internal {
MigrationLike(ASSESSOR_NEW).migrate(ASSESSOR);
// migrate dependencies
DependLike(ASSESSOR_NEW).depend("navFeed", FEED);
DependLike(ASSESSOR_NEW).depend("juniorTranche", JUNIOR_TRANCHE_NEW);
DependLike(ASSESSOR_NEW).depend("seniorTranche", SENIOR_TRANCHE_NEW);
DependLike(ASSESSOR_NEW).depend("reserve", RESERVE_NEW);
DependLike(ASSESSOR_NEW).depend("lending", CLERK);
// migrate permissions
AuthLike(ASSESSOR_NEW).rely(COORDINATOR_NEW);
AuthLike(ASSESSOR_NEW).rely(RESERVE_NEW);
}
function migrateCoordinator() internal {
MigrationLike(COORDINATOR_NEW).migrate(COORDINATOR);
// migrate dependencies
DependLike(COORDINATOR_NEW).depend("assessor", ASSESSOR_NEW);
DependLike(COORDINATOR_NEW).depend("juniorTranche", JUNIOR_TRANCHE_NEW);
DependLike(COORDINATOR_NEW).depend("seniorTranche", SENIOR_TRANCHE_NEW);
DependLike(COORDINATOR_NEW).depend("reserve", RESERVE_NEW);
// migrate permissions
AuthLike(JUNIOR_TRANCHE_NEW).rely(COORDINATOR_NEW);
AuthLike(JUNIOR_TRANCHE).deny(COORDINATOR);
AuthLike(SENIOR_TRANCHE_NEW).rely(COORDINATOR_NEW);
AuthLike(SENIOR_TRANCHE).deny(COORDINATOR);
}
function migrateReserve() internal {
MigrationLike(RESERVE_NEW).migrate(RESERVE);
// migrate dependencies
DependLike(RESERVE_NEW).depend("currency", TINLAKE_CURRENCY);
DependLike(RESERVE_NEW).depend("shelf", SHELF);
DependLike(RESERVE_NEW).depend("lending", CLERK);
DependLike(RESERVE_NEW).depend("pot", RESERVE_NEW);
DependLike(SHELF).depend("distributor", RESERVE_NEW);
DependLike(SHELF).depend("lender", RESERVE_NEW);
DependLike(COLLECTOR).depend("distributor", RESERVE_NEW);
DependLike(JUNIOR_TRANCHE).depend("reserve", RESERVE_NEW);
// migrate permissions
AuthLike(RESERVE_NEW).rely(JUNIOR_TRANCHE_NEW);
AuthLike(RESERVE_NEW).rely(SENIOR_TRANCHE_NEW);
AuthLike(RESERVE_NEW).rely(ASSESSOR_NEW);
// migrate reserve balance
SpellERC20Like currency = SpellERC20Like(TINLAKE_CURRENCY);
uint balanceReserve = currency.balanceOf(RESERVE);
SpellReserveLike(RESERVE).payout(balanceReserve);
currency.transferFrom(address(this), RESERVE_NEW, balanceReserve);
}
function migrateSeniorTranche() internal {
TrancheLike tranche = TrancheLike(SENIOR_TRANCHE_NEW);
require((tranche.totalSupply() == 0 && tranche.totalRedeem() == 0), "tranche-has-orders");
DependLike(SENIOR_TRANCHE_NEW).depend("reserve", RESERVE_NEW);
DependLike(SENIOR_TRANCHE_NEW).depend("coordinator", COORDINATOR_NEW);
DependLike(SENIOR_OPERATOR).depend("tranche", SENIOR_TRANCHE_NEW);
AuthLike(SENIOR_TOKEN).deny(SENIOR_TRANCHE);
AuthLike(SENIOR_TOKEN).rely(SENIOR_TRANCHE_NEW);
AuthLike(SENIOR_TRANCHE_NEW).rely(SENIOR_OPERATOR);
SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(SENIOR_TRANCHE_NEW, type(uint256).max);
}
function migrateJuniorTranche() internal {
TrancheLike tranche = TrancheLike(JUNIOR_TRANCHE_NEW);
require((tranche.totalSupply() == 0 && tranche.totalRedeem() == 0), "tranche-has-orders");
DependLike(JUNIOR_TRANCHE_NEW).depend("reserve", RESERVE_NEW);
DependLike(JUNIOR_TRANCHE_NEW).depend("coordinator", COORDINATOR_NEW);
DependLike(JUNIOR_OPERATOR).depend("tranche", JUNIOR_TRANCHE_NEW);
AuthLike(JUNIOR_TOKEN).deny(JUNIOR_TRANCHE);
AuthLike(JUNIOR_TOKEN).rely(JUNIOR_TRANCHE_NEW);
AuthLike(JUNIOR_TRANCHE_NEW).rely(JUNIOR_OPERATOR);
SpellMemberlistLike(JUNIOR_MEMBERLIST).updateMember(JUNIOR_TRANCHE_NEW, type(uint256).max);
}
function integrateAdapter() internal {
require(SpellERC20Like(RWA_GEM).balanceOf(MAKER_MGR) == 1 ether);
// dependencies
DependLike(CLERK).depend("assessor", ASSESSOR_NEW);
DependLike(CLERK).depend("mgr", MAKER_MGR);
DependLike(CLERK).depend("coordinator", COORDINATOR_NEW);
DependLike(CLERK).depend("reserve", RESERVE_NEW);
DependLike(CLERK).depend("tranche", SENIOR_TRANCHE_NEW);
DependLike(CLERK).depend("collateral", SENIOR_TOKEN);
DependLike(CLERK).depend("spotter", SPOTTER);
DependLike(CLERK).depend("vat", VAT);
DependLike(CLERK).depend("jug", JUG);
FileLike(CLERK).file("buffer", MAT_BUFFER);
// permissions
AuthLike(CLERK).rely(COORDINATOR_NEW);
AuthLike(CLERK).rely(RESERVE_NEW);
AuthLike(SENIOR_TRANCHE_NEW).rely(CLERK);
AuthLike(RESERVE_NEW).rely(CLERK);
AuthLike(ASSESSOR_NEW).rely(CLERK);
// currency
SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(CLERK, type(uint256).max);
SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(MAKER_MGR, type(uint256).max);
// setup mgr
AuthLike(MAKER_MGR).rely(CLERK);
FileLike(MAKER_MGR).file("urn", URN);
FileLike(MAKER_MGR).file("liq", LIQ);
FileLike(MAKER_MGR).file("end", END);
FileLike(MAKER_MGR).file("owner", CLERK);
FileLike(MAKER_MGR).file("pool", SENIOR_OPERATOR);
FileLike(MAKER_MGR).file("tranche", SENIOR_TRANCHE_NEW);
// lock token
MgrLike(MAKER_MGR).lock(1 ether);
}
function setupPoolAdmin() internal {
PoolAdminLike poolAdmin = PoolAdminLike(POOL_ADMIN);
// setup dependencies
DependLike(POOL_ADMIN).depend("assessor", ASSESSOR_NEW);
DependLike(POOL_ADMIN).depend("lending", CLERK);
DependLike(POOL_ADMIN).depend("seniorMemberlist", SENIOR_MEMBERLIST);
DependLike(POOL_ADMIN).depend("juniorMemberlist", JUNIOR_MEMBERLIST);
// setup permissions
AuthLike(ASSESSOR_NEW).rely(POOL_ADMIN);
AuthLike(CLERK).rely(POOL_ADMIN);
AuthLike(JUNIOR_MEMBERLIST).rely(POOL_ADMIN);
AuthLike(SENIOR_MEMBERLIST).rely(POOL_ADMIN);
// directly relying governance so it can be used to directly add/remove pool admins without going through the root
AuthLike(POOL_ADMIN).rely(GOVERNANCE);
// setup admins
poolAdmin.relyAdmin(POOL_ADMIN1);
poolAdmin.relyAdmin(POOL_ADMIN2);
poolAdmin.relyAdmin(POOL_ADMIN3);
poolAdmin.relyAdmin(POOL_ADMIN4);
poolAdmin.relyAdmin(POOL_ADMIN5);
poolAdmin.relyAdmin(POOL_ADMIN6);
poolAdmin.relyAdmin(AO_POOL_ADMIN);
}
function updateRegistry() internal {
PoolRegistryLike(POOL_REGISTRY).file(ROOT_CONTRACT, true, SLUG, IPFS_HASH);
}
}
|
setup dependencies setup permissions directly relying governance so it can be used to directly add/remove pool admins without going through the root setup admins
|
function setupPoolAdmin() internal {
PoolAdminLike poolAdmin = PoolAdminLike(POOL_ADMIN);
DependLike(POOL_ADMIN).depend("assessor", ASSESSOR_NEW);
DependLike(POOL_ADMIN).depend("lending", CLERK);
DependLike(POOL_ADMIN).depend("seniorMemberlist", SENIOR_MEMBERLIST);
DependLike(POOL_ADMIN).depend("juniorMemberlist", JUNIOR_MEMBERLIST);
AuthLike(ASSESSOR_NEW).rely(POOL_ADMIN);
AuthLike(CLERK).rely(POOL_ADMIN);
AuthLike(JUNIOR_MEMBERLIST).rely(POOL_ADMIN);
AuthLike(SENIOR_MEMBERLIST).rely(POOL_ADMIN);
AuthLike(POOL_ADMIN).rely(GOVERNANCE);
poolAdmin.relyAdmin(POOL_ADMIN1);
poolAdmin.relyAdmin(POOL_ADMIN2);
poolAdmin.relyAdmin(POOL_ADMIN3);
poolAdmin.relyAdmin(POOL_ADMIN4);
poolAdmin.relyAdmin(POOL_ADMIN5);
poolAdmin.relyAdmin(POOL_ADMIN6);
poolAdmin.relyAdmin(AO_POOL_ADMIN);
}
| 2,367,764 |
// SPDX-License-Identifier: MIT License
pragma solidity ^0.8.4;
////////////////////////////////
///////////// ERC //////////////
////////////////////////////////
/*
* @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 payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
////////////////////////////////
////////// Dividend ////////////
////////////////////////////////
/*
@title Dividend-Paying Token Interface
@author Roger Wu (https://github.com/roger-wu)
@dev An interface for a dividend-paying token contract.
*/
interface IDividendPayingToken {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/*
@title Dividend-Paying Token Optional Interface
@author Roger Wu (https://github.com/roger-wu)
@dev OPTIONAL functions for a dividend-paying token contract.
*/
interface IDividendPayingTokenOptional {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
/*
@title Dividend-Paying Token
@author Roger Wu (https://github.com/roger-wu)
@dev A mintable ERC20 token that allows anyone to pay and distribute ether
to token holders as dividends and allows token holders to withdraw their dividends.
Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
*/
contract DividendPayingToken is ERC20, IDividendPayingToken, IDividendPayingTokenOptional {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
uint256 internal lastAmount;
address public dividendToken = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
uint256 public gasForTransfer;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
gasForTransfer = 3000;
}
receive() external payable {
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
function distributeDividends(uint256 amount) public {
require(totalSupply() > 0);
if (amount > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(amount).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, amount);
totalDividendsDistributed = totalDividendsDistributed.add(amount);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
function setDividendTokenAddress(address newToken) public {
dividendToken = newToken;
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
bool success = IERC20(dividendToken).transfer(user, _withdrawableDividend);
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
////////////////////////////////
///////// Interfaces ///////////
////////////////////////////////
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
////////////////////////////////
////////// Libraries ///////////
////////////////////////////////
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/**
* @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).
*
* Counter
* part 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;
}
}
/**
* @title SafeMathInt
* @dev Math operations with safety checks that revert on error
* @dev SafeMath adapted for int256
* Based on code of https://github.com/RequestNetwork/requestNetwork/blob/master/packages/requestNetworkSmartContracts/contracts/base/math/SafeMathInt.sol
*/
library SafeMathInt {
function mul(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when multiplying INT256_MIN with -1
// https://github.com/RequestNetwork/requestNetwork/issues/43
require(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1));
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing INT256_MIN by -1
// https://github.com/RequestNetwork/requestNetwork/issues/43
require(!(a == - 2**255 && b == -1) && (b > 0));
return a / b;
}
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;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
////////////////////////////////
/////////// Tokens /////////////
////////////////////////////////
contract XRPU is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private liquidating;
XRPUDividendTracker public dividendTracker;
address public liquidityWallet;
uint256 public constant MAX_BUY_TRANSACTION_AMOUNT = 10000000 * (10**18);
uint256 public constant ETH_REWARDS_FEE = 10;
uint256 public constant LIQUIDITY_FEE = 3;
uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE;
uint256 private maxroutersell;
uint256 private routersell;
bool _swapEnabled = false;
bool openForPresale = false;
bool priceimpactlimit = false;
bool private DynamicTaxEnabled = true;
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
address private _dividendToken = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
bool _maxBuyEnabled = true;
// use by default 150,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 150000;
// liquidate tokens for ETH when the contract reaches 100k tokens by default
uint256 public liquidateTokensAtAmount = 100000 * (10**18);
// whether the token can already be traded
bool public tradingEnabled;
function setswapEnabled(bool swapEnabled) external onlyOwner(){
_swapEnabled = swapEnabled;
}
function settradingEnabled(bool _tradingEnabled) external onlyOwner(){
tradingEnabled = _tradingEnabled;
}
function setDynamicTaxEnabled(bool _setDynamicTaxEnabled) external onlyOwner() {
DynamicTaxEnabled = _setDynamicTaxEnabled;
}
function setPriceImpactLimit(bool _priceimpactlimit) external onlyOwner(){
priceimpactlimit = _priceimpactlimit;
}
function setroutersellamount(uint256 _maxroutersell) external onlyOwner {
maxroutersell = _maxroutersell;
}
function recoverTokens(uint256 tokenAmount) public virtual onlyOwner() {
_approve(address(this), owner(), tokenAmount);
_transfer(address(this), owner(), tokenAmount);
}
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// addresses that can make transfers before presale is over
mapping (address => bool) public canTransferBeforeTradingIsEnabled;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Liquified(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapAndSendToDev(
uint256 tokensSwapped,
uint256 ethReceived
);
event SentDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor() ERC20("XRP Unlimited", "XRPU") {
dividendTracker = new XRPUDividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
// exclude from paying fees or having max transaction amount
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
// enable owner wallet to send tokens before presales are over.
canTransferBeforeTradingIsEnabled[owner()] = true;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 1000000000 * (10**18));
}
receive() external payable {
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "XRPU: The Uniswap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "XRPU: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function excludeFromFees(address account) public onlyOwner {
require(!_isExcludedFromFees[account], "XRPU: Account is already excluded from fees");
_isExcludedFromFees[account] = true;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
require(newValue != gasForProcessing, "XRPU: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns(uint256) {
return dividendTracker.gasForTransfer();
}
function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){
require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee");
_swapEnabled = _devFeeEnabled;
return(_swapEnabled);
}
function setOpenForPresale(bool open )external onlyOwner {
openForPresale = open;
}
function setMaxBuyEnabled(bool enabled ) external onlyOwner {
_maxBuyEnabled = enabled;
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
require(!_isBlackListedBot[account], "Account is already blacklisted");
_isBlackListedBot[account] = true;
_blackListedBots.push(account);
}
function removeBotFromBlackList(address account) external onlyOwner() {
require(_isBlackListedBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _blackListedBots.length; i++) {
if (_blackListedBots[i] == account) {
_blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1];
_isBlackListedBot[account] = false;
_blackListedBots.pop();
break;
}
}
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isBlackListedBot[to], "You have no power here!");
require(!_isBlackListedBot[msg.sender], "You have no power here!");
require(!_isBlackListedBot[from], "You have no power here!");
//to prevent bots both buys and sells will have a max on launch after only sells will
if(from != owner() && to != owner())
if (_maxBuyEnabled){
require(amount <= MAX_BUY_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount.");
}
bool tradingIsEnabled = tradingEnabled;
// only whitelisted addresses can make transfers before the public presale is over.
if (!tradingIsEnabled) {
//turn transfer on to allow for whitelist form/mutlisend presale
if(!openForPresale){
require(canTransferBeforeTradingIsEnabled[from], "XRPU: This account cannot send tokens until trading is enabled");
}
}
if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) {
//require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop");
// require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (!liquidating &&
tradingIsEnabled &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] //no max for those excluded from fees
) {
if (priceimpactlimit) {
require(amount <= balanceOf(uniswapV2Pair).mul(5).div(100));
}
}
uint256 contractTokenBalance = balanceOf(address(this));
if(DynamicTaxEnabled){
if (contractTokenBalance >= (balanceOf(uniswapV2Pair).mul(maxroutersell).div(100))){
contractTokenBalance = (balanceOf(uniswapV2Pair).mul(maxroutersell).div(100));
}
}
routersell = contractTokenBalance;
bool canSwap = contractTokenBalance >= liquidateTokensAtAmount;
if (tradingIsEnabled &&
canSwap &&
_swapEnabled &&
!liquidating &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
liquidating = true;
uint256 swapTokens = routersell.mul(LIQUIDITY_FEE).div(TOTAL_FEES);
swapAndSendToDev(swapTokens);
uint256 sellTokens = routersell.sub(swapTokens);
swapAndSendDividends(sellTokens);
liquidating = false;
}
bool takeFee = tradingIsEnabled && !liquidating;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(TOTAL_FEES).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {
}
if (!liquidating) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
} catch {
}
}
}
function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
address payable _devAndMarketingAddress = payable(0x68F12e2aCfE4e362bD6652530616F395a77173f0);
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, newBalance);
}
function swapTokensForDividendToken(uint256 tokenAmount, address recipient) private {
// generate the uniswap pair path of weth -> busd
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
path[2] = _dividendToken;
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of dividend token
path,
recipient,
block.timestamp
);
}
function swapAndSendDividends(uint256 tokens) private {
swapTokensForDividendToken(tokens, address(this));
uint256 dividends = IERC20(_dividendToken).balanceOf(address(this));
bool success = IERC20(_dividendToken).transfer(address(dividendTracker), dividends);
if (success) {
dividendTracker.distributeDividends(dividends);
emit SentDividends(tokens, dividends);
}
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
}
contract XRPUDividendTracker is DividendPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("XRPU_Dividend_Tracker", "XRPU_Dividend_Tracker") {
claimWait = 1800;
minimumTokenBalanceForDividends = 10000 * (10**18); //must hold 10000+ tokens
}
function _transfer(address, address, uint256) pure internal override {
require(false, "XRPU_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() pure public override {
require(false, "XRPU_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main XRPU contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner {
require(newGasForTransfer != gasForTransfer, "XRPU_Dividend_Tracker: Cannot update gasForTransfer to same value");
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 30 && newClaimWait <= 86400, "XRPU_Dividend_Tracker: claimWait must be updated to between 0.5 min and 24 hours");
require(newClaimWait != claimWait, "XRPU_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
|
View the amount of dividend in wei that an address has earned in total. accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) = (magnifiedDividendPerShare balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude _owner The address of a token holder. return The amount of dividend in wei that `_owner` has earned in total.
|
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
| 167,190 |
./partial_match/1/0xe341fd029DD2d79270DeD847939C99403d7427aA/sources/RONALDO.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("Ronaldo", unicode"罗纳尔多") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 10;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 10000000000000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0x74c4264440f7A555a4C58A47Cd082a62B29B231D);
devWallet = address(0x74c4264440f7A555a4C58A47Cd082a62B29B231D);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(address(marketingWallet), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromMaxTransaction(address(devWallet), true);
excludeFromMaxTransaction(address(marketingWallet), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 9,381,932 |
./full_match/1/0x1af5bcf49647B0162b9fB09420432408D0975aE7/sources/contracts/Rewards.sol
|
Update reward earning of user rewardToken_ The address of the reward token account_ The account totalSupply_ The supply of reference (boosted or locked) balance_ The balance of reference (boosted or locked)/
|
function _updateReward(address rewardToken_, address account_, uint256 totalSupply_, uint256 balance_) private {
uint256 _rewardPerTokenStored = _rewardPerToken(rewardToken_, totalSupply_);
Reward storage _reward = rewards[rewardToken_];
_reward.rewardPerTokenStored = _rewardPerTokenStored;
_reward.lastUpdateTime = lastTimeRewardApplicable(rewardToken_);
if (account_ != address(0)) {
rewardOf[rewardToken_][account_] = UserReward({
claimableRewardsStored: _claimable(rewardToken_, account_, totalSupply_, balance_).toUint128(),
rewardPerTokenPaid: _rewardPerTokenStored.toUint128()
});
}
}
| 2,910,758 |
pragma solidity ^0.5.0;
/// @title Ownable contract - base contract with an owner
contract Ownable {
address public owner;
constructor () public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title ERC20 interface see https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transferFrom(address from, address to, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title SafeMath contract - math operations with safety checks
contract SafeMath {
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
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 PayFair contract - standard ERC20 token with Short Hand Attack and approve() race condition mitigation.
contract PayFair is SafeMath, ERC20, Ownable {
string public name = "PayFair Token";
string public symbol = "PFR";
uint public constant decimals = 8;
uint public constant FROZEN_TOKENS = 11e6;
uint public constant MULTIPLIER = 10 ** decimals;
ERC20 public oldToken;
/// approve() allowances
mapping (address => mapping (address => uint)) allowed;
/// holder balances
mapping(address => uint) balances;
/// @dev Fix for the ERC20 short address attack http://vessenes.com/the-erc20-short-address-attack-explained/
/// @param size payload size
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
/// @dev Constructor
constructor (address oldTokenAdddress) public {
owner = msg.sender;
oldToken = ERC20(oldTokenAdddress);
totalSupply = convertToDecimal(FROZEN_TOKENS);
balances[owner] = convertToDecimal(FROZEN_TOKENS);
}
/// Fallback method will buyout tokens
function() external payable {
revert();
}
function upgradeTokens(uint amountToUpgrade) public {
require(amountToUpgrade <= convertToDecimal(oldToken.balanceOf(msg.sender)));
require(amountToUpgrade <= convertToDecimal(oldToken.allowance(msg.sender, address(this))));
emit Transfer(address(0), msg.sender, amountToUpgrade);
totalSupply = safeAdd(totalSupply, amountToUpgrade);
balances[msg.sender] = safeAdd(balances[msg.sender], amountToUpgrade);
oldToken.transferFrom(msg.sender, address(0x0), amountToUpgrade);
}
/// @dev Converts token value to value with decimal places
/// @param amount Source token value
function convertToDecimal(uint amount) private pure returns (uint) {
return safeMul(amount, MULTIPLIER);
}
/// @dev Tranfer tokens to address
/// @param _to dest address
/// @param _value tokens amount
/// @return transfer result
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/// @dev Tranfer tokens from one address to other
/// @param _from source address
/// @param _to dest address
/// @param _value tokens amount
/// @return transfer result
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool success) {
uint256 _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
emit Transfer(_from, _to, _value);
return true;
}
/// @dev Tokens balance
/// @param _owner holder address
/// @return balance amount
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
/// @dev Approve transfer
/// @param _spender holder address
/// @param _value tokens amount
/// @return result
function approve(address _spender, uint _value) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require ((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Token allowance
/// @param _owner holder address
/// @param _spender spender address
/// @return remain amount
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
|
Token allowance _owner holder address _spender spender address return remain amount
|
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
| 409,107 |
pragma solidity ^0.4.24;
// File: contracts/Genetic.sol
// solhint-disable-next-line
pragma solidity ^0.4.23;
contract Genetic {
// TODO mutations
// maximum number of random mutations per chromatid
uint8 public constant R = 5;
// solhint-disable-next-line function-max-lines
function breed(uint256[2] mother, uint256[2] father, uint256 seed) internal view returns (uint256[2] memOffset) {
// Meiosis I: recombining alleles (Chromosomal crossovers)
// Note about optimization I: no cell duplication,
// producing 2 seeds/eggs per cell is enough, instead of 4 (like humans do)
// Note about optimization II: crossovers happen,
// but only 1 side of the result is computed,
// as the other side will not affect anything.
// solhint-disable-next-line no-inline-assembly
assembly {
// allocate output
// 1) get the pointer to our memory
memOffset := mload(0x40)
// 2) Change the free-memory pointer to keep our memory
// (we will only use 64 bytes: 2 values of 256 bits)
mstore(0x40, add(memOffset, 64))
// Put seed in scratchpad 0
mstore(0x0, seed)
// Also use the timestamp, best we could do to increase randomness
// without increasing costs dramatically. (Trade-off)
mstore(0x20, timestamp)
// Hash it for a universally random bitstring.
let hash := keccak256(0, 64)
// Byzantium VM does not support shift opcodes, will be introduced in Constantinople.
// Soldity itself, in non-assembly, also just uses other opcodes to simulate it.
// Optmizer should take care of inlining, just declare shiftR ourselves here.
// Where possible, better optimization is applied to make it cheaper.
function shiftR(value, offset) -> result {
result := div(value, exp(2, offset))
}
// solhint-disable max-line-length
// m_context << Instruction::SWAP1 << u256(2) << Instruction::EXP << Instruction::SWAP1 << (c_leftSigned ? Instruction::SDIV : Instruction::DIV);
// optimization: although one side consists of multiple chromatids,
// we handle them just as one long chromatid:
// only difference is that a crossover in chromatid i affects chromatid i+1.
// No big deal, order and location is random anyway
function processSide(fatherSrc, motherSrc, rngSrc) -> result {
{
// initial rngSrc bit length: 254 bits
// Run the crossovers
// =====================================================
// Pick some crossovers
// Each crossover is spaced ~64 bits on average.
// To achieve this, we get a random 7 bit number, [0, 128), for each crossover.
// 256 / 64 = 4, we need 4 crossovers,
// and will have 256 / 127 = 2 at least (rounded down).
// Get one bit determining if we should pick DNA from the father,
// or from the mother.
// This changes every crossover. (by swapping father and mother)
{
if eq(and(rngSrc, 0x1), 0) {
// Swap mother and father,
// create a temporary variable (code golf XOR swap costs more in gas)
let temp := fatherSrc
fatherSrc := motherSrc
motherSrc := temp
}
// remove the bit from rng source, 253 rng bits left
rngSrc := shiftR(rngSrc, 1)
}
// Don't push/pop this all the time, we have just enough space on stack.
let mask := 0
// Cap at 4 crossovers, no more than that.
let cap := 0
let crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON)
// remove bits from hash, e.g. 254 - 7 = 247 left.
rngSrc := shiftR(rngSrc, 7)
let crossoverPos := crossoverLen
// optimization: instead of shifting with an opcode we don't have until Constantinople,
// keep track of the a shifted number, updated using multiplications.
let crossoverPosLeading1 := 1
// solhint-disable-next-line no-empty-blocks
for { } and(lt(crossoverPos, 256), lt(cap, 4)) {
crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON)
// remove bits from hash, e.g. 254 - 7 = 247 left.
rngSrc := shiftR(rngSrc, 7)
crossoverPos := add(crossoverPos, crossoverLen)
cap := add(cap, 1)
} {
// Note: we go from right to left in the bit-string.
// Create a mask for this crossover.
// Example:
// 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.....
// |Prev. data ||Crossover here ||remaining data .......
//
// The crossover part is copied from the mother/father to the child.
// Create the bit-mask
// Create a bitstring that ignores the previous data:
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// First create a leading 1, just before the crossover, like:
// 00000000000010000000000000000000000000000000000000000000000000000000000.....
// Then substract 1, to get a long string of 1s
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// Now do the same for the remain part, and xor it.
// leading 1
// 00000000000000000000000000000010000000000000000000000000000000000000000000000000000000000.....
// sub 1
// 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111.....
// xor with other
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111.....
// 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.....
// Use the final shifted 1 of the previous crossover as the start marker
mask := sub(crossoverPosLeading1, 1)
// update for this crossover, (and will be used as start for next crossover)
crossoverPosLeading1 := mul(1, exp(2, crossoverPos))
mask := xor(mask,
sub(crossoverPosLeading1, 1)
)
// Now add the parent data to the child genotype
// E.g.
// Mask: 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000....
// Parent: 10010111001000110101011111001010001011100000000000010011000001000100000001011101111000111....
// Child (pre): 00000000000000000000000000000001111110100101111111000011001010000000101010100000110110110....
// Child (post): 00000000000000110101011111001011111110100101111111000011001010000000101010100000110110110....
// To do this, we run: child_post = child_pre | (mask & father)
result := or(result, and(mask, fatherSrc))
// Swap father and mother, next crossover will take a string from the other.
let temp := fatherSrc
fatherSrc := motherSrc
motherSrc := temp
}
// We still have a left-over part that was not copied yet
// E.g., we have something like:
// Father: | xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxx ....
// Mother: |############ xxxxxxxxxx xxxxxxxxxxxx....
// Child: | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx....
// The ############ still needs to be applied to the child, also,
// this can be done cheaper than in the loop above,
// as we don't have to swap anything for the next crossover or something.
// At this point we have to assume 4 crossovers ran,
// and that we only have 127 - 1 - (4 * 7) = 98 bits of randomness left.
// We stopped at the bit after the crossoverPos index, see "x":
// 000000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.....
// now create a leading 1 at crossoverPos like:
// 000000001000000000000000000000000000000000000000000000000000000000000000000.....
// Sub 1, get the mask for what we had.
// 000000000111111111111111111111111111111111111111111111111111111111111111111.....
// Invert, and we have the final mask:
// 111111111000000000000000000000000000000000000000000000000000000000000000000.....
mask := not(sub(crossoverPosLeading1, 1))
// Apply it to the result
result := or(result, and(mask, fatherSrc))
// Random mutations
// =====================================================
// random mutations
// Put rng source in scratchpad 0
mstore(0x0, rngSrc)
// And some arbitrary padding in scratchpad 1,
// used to create different hashes based on input size changes
mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21)
// Hash it for a universally random bitstring.
// Then reduce the number of 1s by AND-ing it with other *different* hashes.
// Each bit in mutations has a probability of 0.5^5 = 0.03125 = 3.125% to be a 1
let mutations := and(
and(
and(keccak256(0, 32), keccak256(1, 33)),
and(keccak256(2, 34), keccak256(3, 35))
),
keccak256(0, 36)
)
result := xor(result, mutations)
}
}
{
// Get 1 bit of pseudo randomness that will
// determine if side #1 will come from the left, or right side.
// Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on.
let relativeFatherSideLoc := mul(and(hash, 0x1), 0x20) // shift by 5 bits = mul by 2^5=32 (0x20)
// Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on.
let relativeMotherSideLoc := mul(and(hash, 0x2), 0x10) // already shifted by 1, mul by 2^4=16 (0x10)
// Now remove the used 2 bits from the hash, 254 bits remaining now.
hash := div(hash, 4)
// Process the side, load the relevant parent data that will be used.
mstore(memOffset, processSide(
mload(add(father, relativeFatherSideLoc)),
mload(add(mother, relativeMotherSideLoc)),
hash
))
// The other side will be the opposite index: 1 -> 0, 0 -> 1
// Apply it to the location,
// which is either 0x20 (For index 1) or 0x0 for index 0.
relativeFatherSideLoc := xor(relativeFatherSideLoc, 0x20)
relativeMotherSideLoc := xor(relativeMotherSideLoc, 0x20)
mstore(0x0, seed)
// Second argument will be inverse,
// resulting in a different second hash.
mstore(0x20, not(timestamp))
// Now create another hash, for the other side
hash := keccak256(0, 64)
// Process the other side
mstore(add(memOffset, 0x20), processSide(
mload(add(father, relativeFatherSideLoc)),
mload(add(mother, relativeMotherSideLoc)),
hash
))
}
}
// Sample input:
// ["0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC","0x4444444455555555555555556666666666666644444444455555555555666666"]
//
// ["0x1111111111112222222223333311111111122222223333333331111112222222","0x7777788888888888999999999999977777777777788888888888999999997777"]
// Expected results (or similar, depends on the seed):
// 0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC < Father side A
// 0x4444444455555555555555556666666666666644444444455555555555666666 < Father side B
// 0x1111111111112222222223333311111111122222223333333331111112222222 < Mother side A
// 0x7777788888888888999999999999977777777777788888888888999999997777 < Mother side B
// xxxxxxxxxxxxxxxxx xxxxxxxxx xx
// 0xAAABBBBBBBBCCCCCD99999999998BBBBBBBBF77778888888888899999999774C < Child side A
// xxx xxxxxxxxxxx
// 0x4441111111112222222223333366666666666222223333333331111112222222 < Child side B
// And then random mutations, for gene pool expansion.
// Each bit is flipped with a 3.125% chance
// Example:
//a2c37edc61dca0ca0b199e098c80fd5a221c2ad03605b4b54332361358745042 < random hash 1
//c217d04b19a83fe497c1cf6e1e10030e455a0812a6949282feec27d67fe2baa7 < random hash 2
//2636a55f38bed26d804c63a13628e21b2d701c902ca37b2b0ca94fada3821364 < random hash 3
//86bb023a85e2da50ac233b946346a53aa070943b0a8e91c56e42ba181729a5f9 < random hash 4
//5d71456a1288ab30ddd4c955384d42e66a09d424bd7743791e3eab8e09aa13f1 < random hash 5
//0000000800800000000000000000000200000000000000000000020000000000 < resulting mutation
//aaabbbbbbbbcccccd99999999998bbbbbbbbf77778888888888899999999774c < original
//aaabbbb3bb3cccccd99999999998bbb9bbbbf7777888888888889b999999774c < mutated (= original XOR mutation)
}
// Generates (psuedo) random Pepe DNA
function randomDNA(uint256 seed) internal pure returns (uint256[2] memOffset) {
// solhint-disable-next-line no-inline-assembly
assembly {
// allocate output
// 1) get the pointer to our memory
memOffset := mload(0x40)
// 2) Change the free-memory pointer to keep our memory
// (we will only use 64 bytes: 2 values of 256 bits)
mstore(0x40, add(memOffset, 64))
// Load the seed into 1st scratchpad memory slot.
// adjacent to the additional value (used to create two distinct hashes)
mstore(0x0, seed)
// In second scratchpad slot:
// The additional value can be any word, as long as the caller uses
// it (second hash needs to be different)
mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21)
// // Create first element pointer of array
// mstore(memOffset, add(memOffset, 64)) // pointer 1
// mstore(add(memOffset, 32), add(memOffset, 96)) // pointer 2
// control block to auto-pop the hash.
{
// L * N * 2 * 4 = 4 * 2 * 2 * 4 = 64 bytes, 2x 256 bit hash
// Sha3 is cheaper than sha256, make use of it
let hash := keccak256(0, 64)
// Store first array value
mstore(memOffset, hash)
// Now hash again, but only 32 bytes of input,
// to ignore make the input different than the previous call,
hash := keccak256(0, 32)
mstore(add(memOffset, 32), hash)
}
}
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/Usernames.sol
// solhint-disable-next-line
pragma solidity ^0.4.19;
contract Usernames {
mapping(address => bytes32) public addressToUser;
mapping(bytes32 => address) public userToAddress;
event UserNamed(address indexed user, bytes32 indexed username);
/**
* Claim a username. Frees up a previously used one
* @param _username to claim
*/
function claimUsername(bytes32 _username) external {
require(userToAddress[_username] == address(0));// Username must be free
if (addressToUser[msg.sender] != bytes32(0)) { // If user already has username free it up
userToAddress[addressToUser[msg.sender]] = address(0);
}
//all is well assign username
addressToUser[msg.sender] = _username;
userToAddress[_username] = msg.sender;
emit UserNamed(msg.sender, _username);
}
}
// File: contracts/Beneficiary.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
/** @title Beneficiary */
contract Beneficiary is Ownable {
address public beneficiary;
constructor() public {
beneficiary = msg.sender;
}
/**
* @dev Change the beneficiary address
* @param _beneficiary Address of the new beneficiary
*/
function setBeneficiary(address _beneficiary) public onlyOwner {
beneficiary = _beneficiary;
}
}
// File: contracts/Affiliate.sol
// solhint-disable-next-line
pragma solidity ^0.4.25;
/** @title Affiliate */
contract Affiliate is Ownable {
mapping(address => bool) public canSetAffiliate;
mapping(address => address) public userToAffiliate;
/** @dev Allows an address to set the affiliate address for a user
* @param _setter The address that should be allowed
*/
function setAffiliateSetter(address _setter) public onlyOwner {
canSetAffiliate[_setter] = true;
}
/**
* @dev Set the affiliate of a user
* @param _user user to set affiliate for
* @param _affiliate address to set
*/
function setAffiliate(address _user, address _affiliate) public {
require(canSetAffiliate[msg.sender]);
if (userToAffiliate[_user] == address(0)) {
userToAffiliate[_user] = _affiliate;
}
}
}
// File: contracts/interfaces/ERC721.sol
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) ;
function transfer(address _to, uint256 _tokenId) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed 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);
}
// File: contracts/interfaces/PepeInterface.sol
contract PepeInterface is ERC721{
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) public returns (bool);
function getCozyAgain(uint256 _pepeId) public view returns(uint64);
}
// File: contracts/AuctionBase.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
/** @title AuctionBase */
contract AuctionBase is Beneficiary {
mapping(uint256 => PepeAuction) public auctions;//maps pepes to auctions
PepeInterface public pepeContract;
Affiliate public affiliateContract;
uint256 public fee = 37500; //in 1 10000th of a percent so 3.75% at the start
uint256 public constant FEE_DIVIDER = 1000000; //Perhaps needs better name?
struct PepeAuction {
address seller;
uint256 pepeId;
uint64 auctionBegin;
uint64 auctionEnd;
uint256 beginPrice;
uint256 endPrice;
}
event AuctionWon(uint256 indexed pepe, address indexed winner, address indexed seller);
event AuctionStarted(uint256 indexed pepe, address indexed seller);
event AuctionFinalized(uint256 indexed pepe, address indexed seller);
constructor(address _pepeContract, address _affiliateContract) public {
pepeContract = PepeInterface(_pepeContract);
affiliateContract = Affiliate(_affiliateContract);
}
/**
* @dev Return a pepe from a auction that has passed
* @param _pepeId the id of the pepe to save
*/
function savePepe(uint256 _pepeId) external {
// solhint-disable-next-line not-rely-on-time
require(auctions[_pepeId].auctionEnd < now);//auction must have ended
require(pepeContract.transfer(auctions[_pepeId].seller, _pepeId));//transfer pepe back to seller
emit AuctionFinalized(_pepeId, auctions[_pepeId].seller);
delete auctions[_pepeId];//delete auction
}
/**
* @dev change the fee on pepe sales. Can only be lowerred
* @param _fee The new fee to set. Must be lower than current fee
*/
function changeFee(uint256 _fee) external onlyOwner {
require(_fee < fee);//fee can not be raised
fee = _fee;
}
/**
* @dev Start a auction
* @param _pepeId Pepe to sell
* @param _beginPrice Price at which the auction starts
* @param _endPrice Ending price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
require(pepeContract.transferFrom(msg.sender, address(this), _pepeId));
// solhint-disable-next-line not-rely-on-time
require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active
PepeAuction memory auction;
auction.seller = msg.sender;
auction.pepeId = _pepeId;
// solhint-disable-next-line not-rely-on-time
auction.auctionBegin = uint64(now);
// solhint-disable-next-line not-rely-on-time
auction.auctionEnd = uint64(now) + _duration;
require(auction.auctionEnd > auction.auctionBegin);
auction.beginPrice = _beginPrice;
auction.endPrice = _endPrice;
auctions[_pepeId] = auction;
emit AuctionStarted(_pepeId, msg.sender);
}
/**
* @dev directly start a auction from the PepeBase contract
* @param _pepeId Pepe to put on auction
* @param _beginPrice Price at which the auction starts
* @param _endPrice Ending price of the auction
* @param _duration How long the auction should take
* @param _seller The address selling the pepe
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
require(msg.sender == address(pepeContract)); //can only be called by pepeContract
//solhint-disable-next-line not-rely-on-time
require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active
PepeAuction memory auction;
auction.seller = _seller;
auction.pepeId = _pepeId;
// solhint-disable-next-line not-rely-on-time
auction.auctionBegin = uint64(now);
// solhint-disable-next-line not-rely-on-time
auction.auctionEnd = uint64(now) + _duration;
require(auction.auctionEnd > auction.auctionBegin);
auction.beginPrice = _beginPrice;
auction.endPrice = _endPrice;
auctions[_pepeId] = auction;
emit AuctionStarted(_pepeId, _seller);
}
/**
* @dev Calculate the current price of a auction
* @param _pepeId the pepeID to calculate the current price for
* @return currentBid the current price for the auction
*/
function calculateBid(uint256 _pepeId) public view returns(uint256 currentBid) {
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = now - auctions[_pepeId].auctionBegin;
// If auction ended return auction end price.
// solhint-disable-next-line not-rely-on-time
if (now >= auction.auctionEnd) {
return auction.endPrice;
} else {
// Can be negative
int256 priceDifference = int256(auction.endPrice) - int256(auction.beginPrice);
// Always positive
int256 duration = int256(auction.auctionEnd) - int256(auction.auctionBegin);
// As already proven in practice by CryptoKitties:
// timePassed -> 64 bits at most
// priceDifference -> 128 bits at most
// timePassed * priceDifference -> 64 + 128 bits at most
int256 priceChange = priceDifference * int256(timePassed) / duration;
// Will be positive, both operands are less than 256 bits
int256 price = int256(auction.beginPrice) + priceChange;
return uint256(price);
}
}
/**
* @dev collect the fees from the auction
*/
function getFees() public {
beneficiary.transfer(address(this).balance);
}
}
// File: contracts/CozyTimeAuction.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
/** @title CozyTimeAuction */
contract CozyTimeAuction is AuctionBase {
// solhint-disable-next-line
constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public {
}
/**
* @dev Start an auction
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuction(_pepeId, _beginPrice, _endPrice, _duration);
}
/**
* @dev Start a auction direclty from the PepeBase smartcontract
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
* @param _seller The address of the seller
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller);
}
/**
* @dev Buy cozy right from the auction
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
*/
// solhint-disable-next-line max-line-length
function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable {
require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
require(now < auction.auctionEnd);// auction must be still going
uint256 price = calculateBid(_pepeId);
require(msg.value >= price);//must send enough ether
uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed?
//Send ETH to seller
auction.seller.transfer(price - totalFee);
//send ETH to beneficiary
address affiliate = affiliateContract.userToAffiliate(_pepeReceiver);
//solhint-disable-next-line
if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate
//nothing just to suppress warning
}
//actual cozytiming
if (_candidateAsFather) {
if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) {
revert();
}
} else {
// Swap around the two pepes, they have no set gender, the user decides what they are.
if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) {
revert();
}
}
//Send pepe to seller of auction
if (!pepeContract.transfer(auction.seller, _pepeId)) {
revert(); //can't complete transfer if this fails
}
if (msg.value > price) { //return ether send to much
_pepeReceiver.transfer(msg.value - price);
}
emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event
delete auctions[_pepeId];//deletes auction
}
/**
* @dev Buy cozytime and pass along affiliate
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
* @param _affiliate Affiliate address to set
*/
//solhint-disable-next-line max-line-length
function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable {
affiliateContract.setAffiliate(_pepeReceiver, _affiliate);
buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver);
}
}
// File: contracts/Haltable.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
contract Haltable is Ownable {
uint256 public haltTime; //when the contract was halted
bool public halted;//is the contract halted?
uint256 public haltDuration;
uint256 public maxHaltDuration = 8 weeks;//how long the contract can be halted
modifier stopWhenHalted {
require(!halted);
_;
}
modifier onlyWhenHalted {
require(halted);
_;
}
/**
* @dev Halt the contract for a set time smaller than maxHaltDuration
* @param _duration Duration how long the contract should be halted. Must be smaller than maxHaltDuration
*/
function halt(uint256 _duration) public onlyOwner {
require(haltTime == 0); //cannot halt if it was halted before
require(_duration <= maxHaltDuration);//cannot halt for longer than maxHaltDuration
haltDuration = _duration;
halted = true;
// solhint-disable-next-line not-rely-on-time
haltTime = now;
}
/**
* @dev Unhalt the contract. Can only be called by the owner or when the haltTime has passed
*/
function unhalt() public {
// solhint-disable-next-line
require(now > haltTime + haltDuration || msg.sender == owner);//unhalting is only possible when haltTime has passed or the owner unhalts
halted = false;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/interfaces/ERC721TokenReceiver.sol
/// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. 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)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
// File: contracts/PepeBase.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
// solhint-disable func-order
contract PepeBase is Genetic, Ownable, Usernames, Haltable {
uint32[15] public cozyCoolDowns = [ //determined by generation / 2
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(15 minutes),
uint32(30 minutes),
uint32(45 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
struct Pepe {
address master; //The master of the pepe
uint256[2] genotype; //all genes stored here
uint64 canCozyAgain; //time when pepe can have nice time again
uint64 generation; //what generation?
uint64 father; //father of this pepe
uint64 mother; //mommy of this pepe
uint8 coolDownIndex;
}
mapping(uint256 => bytes32) public pepeNames;
//stores all pepes
Pepe[] public pepes;
bool public implementsERC721 = true; //signal erc721 support
// solhint-disable-next-line const-name-snakecase
string public constant name = "Crypto Pepe";
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "CPEP";
mapping(address => uint256[]) private wallets;
mapping(address => uint256) public balances; //amounts of pepes per address
mapping(uint256 => address) public approved; //pepe index to address approved to transfer
mapping(address => mapping(address => bool)) public approvedForAll;
uint256 public zeroGenPepes; //how many zero gen pepes are mined
uint256 public constant MAX_PREMINE = 100;//how many pepes can be premined
uint256 public constant MAX_ZERO_GEN_PEPES = 1100; //max number of zero gen pepes
address public miner; //address of the miner contract
modifier onlyPepeMaster(uint256 _pepeId) {
require(pepes[_pepeId].master == msg.sender);
_;
}
modifier onlyAllowed(uint256 _tokenId) {
// solhint-disable-next-line max-line-length
require(msg.sender == pepes[_tokenId].master || msg.sender == approved[_tokenId] || approvedForAll[pepes[_tokenId].master][msg.sender]); //check if msg.sender is allowed
_;
}
event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId);
event PepeNamed(uint256 indexed pepeId);
constructor() public {
Pepe memory pepe0 = Pepe({
master: 0x0,
genotype: [uint256(0), uint256(0)],
canCozyAgain: 0,
father: 0,
mother: 0,
generation: 0,
coolDownIndex: 0
});
pepes.push(pepe0);
}
/**
* @dev Internal function that creates a new pepe
* @param _genoType DNA of the new pepe
* @param _mother The ID of the mother
* @param _father The ID of the father
* @param _generation The generation of the new Pepe
* @param _master The owner of this new Pepe
* @return The ID of the newly generated Pepe
*/
// solhint-disable-next-line max-line-length
function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) {
uint8 tempCoolDownIndex;
tempCoolDownIndex = uint8(_generation / 2);
if (_generation > 28) {
tempCoolDownIndex = 14;
}
Pepe memory _pepe = Pepe({
master: _master, //The master of the pepe
genotype: _genoType, //all genes stored here
canCozyAgain: 0, //time when pepe can have nice time again
father: _father, //father of this pepe
mother: _mother, //mommy of this pepe
generation: _generation, //what generation?
coolDownIndex: tempCoolDownIndex
});
if (_generation == 0) {
zeroGenPepes += 1; //count zero gen pepes
}
//push returns the new length, use it to get a new unique id
pepeId = pepes.push(_pepe) - 1;
//add it to the wallet of the master of the new pepe
addToWallet(_master, pepeId);
emit PepeBorn(_mother, _father, pepeId);
emit Transfer(address(0), _master, pepeId);
return pepeId;
}
/**
* @dev Set the miner contract. Can only be called once
* @param _miner Address of the miner contract
*/
function setMiner(address _miner) public onlyOwner {
require(miner == address(0));//can only be set once
miner = _miner;
}
/**
* @dev Mine a new Pepe. Can only be called by the miner contract.
* @param _seed Seed to be used for the generation of the DNA
* @param _receiver Address receiving the newly mined Pepe
* @return The ID of the newly mined Pepe
*/
function minePepe(uint256 _seed, address _receiver) public stopWhenHalted returns(uint256) {
require(msg.sender == miner);//only miner contract can call
require(zeroGenPepes < MAX_ZERO_GEN_PEPES);
return _newPepe(randomDNA(_seed), 0, 0, 0, _receiver);
}
/**
* @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE
* @param _amount Amount of Pepes to premine
*/
function pepePremine(uint256 _amount) public onlyOwner stopWhenHalted {
for (uint i = 0; i < _amount; i++) {
require(zeroGenPepes <= MAX_PREMINE);//can only generate set amount during premine
//create a new pepe
// 1) who's genes are based on hash of the timestamp and the number of pepes
// 2) who has no mother or father
// 3) who is generation zero
// 4) who's master is the manager
// solhint-disable-next-line
_newPepe(randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, pepes.length)))), 0, 0, 0, owner);
}
}
/**
* @dev CozyTime two Pepes together
* @param _mother The mother of the new Pepe
* @param _father The father of the new Pepe
* @param _pepeReceiver Address receiving the new Pepe
* @return If it was a success
*/
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external stopWhenHalted returns (bool) {
//cannot cozyTime with itself
require(_mother != _father);
//caller has to either be master or approved for mother
// solhint-disable-next-line max-line-length
require(pepes[_mother].master == msg.sender || approved[_mother] == msg.sender || approvedForAll[pepes[_mother].master][msg.sender]);
//caller has to either be master or approved for father
// solhint-disable-next-line max-line-length
require(pepes[_father].master == msg.sender || approved[_father] == msg.sender || approvedForAll[pepes[_father].master][msg.sender]);
//require both parents to be ready for cozytime
// solhint-disable-next-line not-rely-on-time
require(now > pepes[_mother].canCozyAgain && now > pepes[_father].canCozyAgain);
//require both mother parents not to be father
require(pepes[_mother].mother != _father && pepes[_mother].father != _father);
//require both father parents not to be mother
require(pepes[_father].mother != _mother && pepes[_father].father != _mother);
Pepe storage father = pepes[_father];
Pepe storage mother = pepes[_mother];
approved[_father] = address(0);
approved[_mother] = address(0);
uint256[2] memory newGenotype = breed(father.genotype, mother.genotype, pepes.length);
uint64 newGeneration;
newGeneration = mother.generation + 1;
if (newGeneration < father.generation + 1) { //if father generation is bigger
newGeneration = father.generation + 1;
}
_handleCoolDown(_mother);
_handleCoolDown(_father);
//sets pepe birth when mother is done
// solhint-disable-next-line max-line-length
pepes[_newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver)].canCozyAgain = mother.canCozyAgain; //_pepeReceiver becomes the master of the pepe
return true;
}
/**
* @dev Internal function to increase the coolDownIndex
* @param _pepeId The id of the Pepe to update the coolDown of
*/
function _handleCoolDown(uint256 _pepeId) internal {
Pepe storage tempPep = pepes[_pepeId];
// solhint-disable-next-line not-rely-on-time
tempPep.canCozyAgain = uint64(now + cozyCoolDowns[tempPep.coolDownIndex]);
if (tempPep.coolDownIndex < 14) {// after every cozy time pepe gets slower
tempPep.coolDownIndex++;
}
}
/**
* @dev Set the name of a Pepe. Can only be set once
* @param _pepeId ID of the pepe to name
* @param _name The name to assign
*/
function setPepeName(uint256 _pepeId, bytes32 _name) public stopWhenHalted onlyPepeMaster(_pepeId) returns(bool) {
require(pepeNames[_pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000);
pepeNames[_pepeId] = _name;
emit PepeNamed(_pepeId);
return true;
}
/**
* @dev Transfer a Pepe to the auction contract and auction it
* @param _pepeId ID of the Pepe to auction
* @param _auction Auction contract address
* @param _beginPrice Price the auction starts at
* @param _endPrice Price the auction ends at
* @param _duration How long the auction should run
*/
// solhint-disable-next-line max-line-length
function transferAndAuction(uint256 _pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public stopWhenHalted onlyPepeMaster(_pepeId) {
_transfer(msg.sender, _auction, _pepeId);//transfer pepe to auction
AuctionBase auction = AuctionBase(_auction);
auction.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, msg.sender);
}
/**
* @dev Approve and buy. Used to buy cozyTime in one call
* @param _pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
*/
// solhint-disable-next-line max-line-length
function approveAndBuy(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) {
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
CozyTimeAuction(_auction).buyCozy.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender); //breeding resets approval
}
/**
* @dev The same as above only pass an extra parameter
* @param _pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
* @param _affiliate Address to set as affiliate
*/
// solhint-disable-next-line max-line-length
function approveAndBuyAffiliated(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) {
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
CozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); //breeding resets approval
}
/**
* @dev get Pepe information
* @param _pepeId ID of the Pepe to get information of
* @return master
* @return genotype
* @return canCozyAgain
* @return generation
* @return father
* @return mother
* @return pepeName
* @return coolDownIndex
*/
// solhint-disable-next-line max-line-length
function getPepe(uint256 _pepeId) public view returns(address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) {
Pepe storage tempPep = pepes[_pepeId];
master = tempPep.master;
genotype = tempPep.genotype;
canCozyAgain = tempPep.canCozyAgain;
generation = tempPep.generation;
father = tempPep.father;
mother = tempPep.mother;
pepeName = pepeNames[_pepeId];
coolDownIndex = tempPep.coolDownIndex;
}
/**
* @dev Get the time when a pepe can cozy again
* @param _pepeId ID of the pepe
* @return Time when the pepe can cozy again
*/
function getCozyAgain(uint256 _pepeId) public view returns(uint64) {
return pepes[_pepeId].canCozyAgain;
}
/**
* ERC721 Compatibility
*
*/
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev Get the total number of Pepes
* @return total Returns the total number of pepes
*/
function totalSupply() public view returns(uint256 total) {
total = pepes.length - balances[address(0)];
return total;
}
/**
* @dev Get the number of pepes owned by an address
* @param _owner Address to get the balance from
* @return balance The number of pepes
*/
function balanceOf(address _owner) external view returns (uint256 balance) {
balance = balances[_owner];
}
/**
* @dev Get the owner of a Pepe
* @param _tokenId the token to get the owner of
* @return _owner the owner of the pepe
*/
function ownerOf(uint256 _tokenId) external view returns (address _owner) {
_owner = pepes[_tokenId].master;
}
/**
* @dev Get the id of an token by its index
* @param _owner The address to look up the tokens of
* @param _index Index to look at
* @return tokenId the ID of the token of the owner at the specified index
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 tokenId) {
//The index must be smaller than the balance,
// to guarantee that there is no leftover token returned.
require(_index < balances[_owner]);
return wallets[_owner][_index];
}
/**
* @dev Private method that ads a token to the wallet
* @param _owner Address of the owner
* @param _tokenId Pepe ID to add
*/
function addToWallet(address _owner, uint256 _tokenId) private {
uint256[] storage wallet = wallets[_owner];
uint256 balance = balances[_owner];
if (balance < wallet.length) {
wallet[balance] = _tokenId;
} else {
wallet.push(_tokenId);
}
//increase owner balance
//overflow is not likely to happen(need very large amount of pepes)
balances[_owner] += 1;
}
/**
* @dev Remove a token from a address's wallet
* @param _owner Address of the owner
* @param _tokenId Token to remove from the wallet
*/
function removeFromWallet(address _owner, uint256 _tokenId) private {
uint256[] storage wallet = wallets[_owner];
uint256 i = 0;
// solhint-disable-next-line no-empty-blocks
for (; wallet[i] != _tokenId; i++) {
// not the pepe we are looking for
}
if (wallet[i] == _tokenId) {
//found it!
uint256 last = balances[_owner] - 1;
if (last > 0) {
//move the last item to this spot, the last will become inaccessible
wallet[i] = wallet[last];
}
//else: no last item to move, the balance is 0, making everything inaccessible.
//only decrease balance if _tokenId was in the wallet
balances[_owner] -= 1;
}
}
/**
* @dev Internal transfer function
* @param _from Address sending the token
* @param _to Address to token is send to
* @param _tokenId ID of the token to send
*/
function _transfer(address _from, address _to, uint256 _tokenId) internal {
pepes[_tokenId].master = _to;
approved[_tokenId] = address(0);//reset approved of pepe on every transfer
//remove the token from the _from wallet
removeFromWallet(_from, _tokenId);
//add the token to the _to wallet
addToWallet(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev transfer a token. Can only be called by the owner of the token
* @param _to Addres to send the token to
* @param _tokenId ID of the token to send
*/
// solhint-disable-next-line no-simple-event-func-name
function transfer(address _to, uint256 _tokenId) public stopWhenHalted
onlyPepeMaster(_tokenId) //check if msg.sender is the master of this pepe
returns(bool)
{
_transfer(msg.sender, _to, _tokenId);//after master modifier invoke internal transfer
return true;
}
/**
* @dev Approve a address to send a token
* @param _to Address to approve
* @param _tokenId Token to set approval for
*/
function approve(address _to, uint256 _tokenId) external stopWhenHalted
onlyPepeMaster(_tokenId)
{
approved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/**
* @dev Approve or revoke approval an address for al tokens of a user
* @param _operator Address to (un)approve
* @param _approved Approving or revoking indicator
*/
function setApprovalForAll(address _operator, bool _approved) external stopWhenHalted {
if (_approved) {
approvedForAll[msg.sender][_operator] = true;
} else {
approvedForAll[msg.sender][_operator] = false;
}
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get approved address for a token
* @param _tokenId Token ID to get the approved address for
* @return The address that is approved for this token
*/
function getApproved(uint256 _tokenId) external view returns (address) {
return approved[_tokenId];
}
/**
* @dev Get if an operator is approved for all tokens of that owner
* @param _owner Owner to check the approval for
* @param _operator Operator to check approval for
* @return Boolean indicating if the operator is approved for that owner
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return approvedForAll[_owner][_operator];
}
/**
* @dev Function to signal support for an interface
* @param interfaceID the ID of the interface to check for
* @return Boolean indicating support
*/
function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
if (interfaceID == 0x80ac58cd || interfaceID == 0x01ffc9a7) { //TODO: add more interfaces the contract supports
return true;
}
return false;
}
/**
* @dev Safe transferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external stopWhenHalted {
_safeTransferFromInternal(_from, _to, _tokenId, "");
}
/**
* @dev Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external stopWhenHalted {
_safeTransferFromInternal(_from, _to, _tokenId, _data);
}
/**
* @dev Internal Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function _safeTransferFromInternal(address _from, address _to, uint256 _tokenId, bytes _data) internal onlyAllowed(_tokenId) {
require(pepes[_tokenId].master == _from);//check if from is current owner
require(_to != address(0));//throw on zero address
_transfer(_from, _to, _tokenId); //transfer token
if (isContract(_to)) { //check if is contract
// solhint-disable-next-line max-line-length
require(ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/**
* @dev TransferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @return If it was successful
*/
// solhint-disable-next-line max-line-length
function transferFrom(address _from, address _to, uint256 _tokenId) public stopWhenHalted onlyAllowed(_tokenId) returns(bool) {
require(pepes[_tokenId].master == _from);//check if _from is really the master.
require(_to != address(0));
_transfer(_from, _to, _tokenId);//handles event, balances and approval reset;
return true;
}
/**
* @dev Utility method to check if an address is a contract
* @param _address Address to check
* @return Boolean indicating if the address is a contract
*/
function isContract(address _address) internal view returns (bool) {
uint size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_address) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/PepToken.sol
// solhint-disable-next-line
pragma solidity ^0.4.24;
contract PepToken is StandardToken {
string public name = "PEP Token";
string public symbol = "PEP";
uint8 public decimals = 18;
uint256 public constant INITIAL_BALANCE = 45000000 ether;
constructor() public {
balances[msg.sender] = INITIAL_BALANCE;
totalSupply_ = INITIAL_BALANCE;
}
/**
* @dev Allow spender to revoke its own allowance
* @param _from Address from which allowance should be revoked
*/
function revokeAllowance(address _from) public {
allowed[_from][msg.sender] = 0;
}
}
// File: contracts/PepeGrinder.sol
// solhint-disable-next-line
pragma solidity ^0.4.4;
contract PepeGrinder is StandardToken, Ownable {
address public pepeContract;
address public miner;
uint256[] public pepes;
mapping(address => bool) public dusting;
string public name = "CryptoPepes DUST";
string public symbol = "DPEP";
uint8 public decimals = 18;
uint256 public constant DUST_PER_PEPE = 100 ether;
constructor(address _pepeContract) public {
pepeContract = _pepeContract;
}
/**
* Set the mining contract. Can only be set once
* @param _miner The address of the miner contract
*/
function setMiner(address _miner) public onlyOwner {
require(miner == address(0));// can only be set once
miner = _miner;
}
/**
* Gets called by miners who wanna dust their mined Pepes
*/
function setDusting() public {
dusting[msg.sender] = true;
}
/**
* Dust a pepe to pepeDust
* @param _pepeId Pepe to dust
* @param _miner address of the miner
*/
function dustPepe(uint256 _pepeId, address _miner) public {
require(msg.sender == miner);
balances[_miner] += DUST_PER_PEPE;
pepes.push(_pepeId);
totalSupply_ += DUST_PER_PEPE;
emit Transfer(address(0), _miner, DUST_PER_PEPE);
}
/**
* Convert dust into a Pepe
*/
function claimPepe() public {
require(balances[msg.sender] >= DUST_PER_PEPE);
balances[msg.sender] -= DUST_PER_PEPE; //change balance and total supply
totalSupply_ -= DUST_PER_PEPE;
PepeBase(pepeContract).transfer(msg.sender, pepes[pepes.length-1]);//transfer pepe
pepes.length -= 1;
emit Transfer(msg.sender, address(0), DUST_PER_PEPE);
}
}
// File: contracts/Math/ExtendedMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library ExtendedMath {
//return the smaller of the two inputs (a or b)
function limitLessThan(uint a, uint b) internal pure returns (uint c) {
if(a > b) return b;
return a;
}
}
// File: contracts/Mining.sol
// solhint-disable-next-line
pragma solidity ^0.4.4;
// solhint-disable max-line-length
// solhint-disable-next-line
contract Mining is Beneficiary {
using SafeMath for uint;
using ExtendedMath for uint;
uint public latestDifficultyPeriodStarted = block.number;
uint public epochCount = 0;//number of 'blocks' mined
uint public constant MAX_EPOCH_COUNT = 16000;
uint public baseMiningReward = 2500 ether;
uint public blocksPerReadjustment = 20;
uint public tokensMinted;
// solhint-disable var-name-mixedcase
uint public _MINIMUM_TARGET = 2**16;
uint public _MAXIMUM_TARGET = 2**250; //Testing setting!
//uint public _MAXIMUM_TARGET = 2**230; //SHOULD MAKE THIS HARDER IN PRODUCTION
uint public constant STARTING_DIFFICULTY = 0x00000000000b4963208fc24a4a15e9ea7c1556f9583f1941a7515fabbd194584;
bytes32 public challengeNumber;
uint public difficulty;
uint public MINING_RATE_FACTOR = 31; //mint the token 31 times less often than ether
//difficulty adjustment parameters- be careful modifying these
uint public MAX_ADJUSTMENT_PERCENT = 100;
uint public TARGET_DIVISOR = 2000;
uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2);
mapping(bytes32 => bytes32) public solutionForChallenge;
Statistics public statistics;
PepeBase public pepeContract;
PepToken public pepToken;
PepeGrinder public pepeGrinder;
uint256 public miningStart;//timestamp when mining starts
event Mint(address indexed from, uint rewardAmount, uint epochCount, bytes32 newChallengeNumber);
// track read only minting statistics
struct Statistics {
address lastRewardTo;
uint lastRewardAmount;
uint lastRewardEthBlockNumber;
uint lastRewardTimestamp;
}
constructor(address _pepeContract, address _pepToken, address _pepeGrinder, uint256 _miningStart) public {
pepeContract = PepeBase(_pepeContract);
pepToken = PepToken(_pepToken);
pepeGrinder = PepeGrinder(_pepeGrinder);
difficulty = STARTING_DIFFICULTY;
miningStart = _miningStart;
}
/**
* Mint a new pepe if noce is correct
* @param nonce The nonce to submit
* @param challengeDigest The resulting digest
* @return success Boolean indicating if mint was successful
*/
// solhint-disable-next-line
function mint(uint256 nonce, bytes32 challengeDigest) public returns (bool success) {
require(epochCount < MAX_EPOCH_COUNT);//max 16k blocks
// solhint-disable-next-line not-rely-on-time
require(now > miningStart);
// perform the hash function validation
_hash(nonce, challengeDigest);
// calculate the current reward
uint rewardAmount = _reward(nonce);
// increment the minted tokens amount
tokensMinted += rewardAmount;
epochCount += 1;
challengeNumber = blockhash(block.number - 1);
_adjustDifficulty();
//populate read only diagnostics data
// solhint-disable-next-line not-rely-on-time
statistics = Statistics(msg.sender, rewardAmount, block.number, now);
// send Mint event indicating a successful implementation
emit Mint(msg.sender, rewardAmount, epochCount, challengeNumber);
if (epochCount == MAX_EPOCH_COUNT) { //destroy this smart contract on the latest block
selfdestruct(msg.sender);
}
return true;
}
/**
* Get the current challengeNumber
* @return bytes32 challengeNumber
*/
function getChallengeNumber() public constant returns (bytes32) {
return challengeNumber;
}
/**
* Get the current mining difficulty
* @return the current difficulty
*/
function getMiningDifficulty() public constant returns (uint) {
return _MAXIMUM_TARGET.div(difficulty);
}
/**
* Get the mining target
* @return The current mining target
*/
function getMiningTarget() public constant returns (uint256) {
return difficulty;
}
/**
* Get the mining reward
* @return The current mining reward. Always 2500PEP
*/
function getMiningReward() public constant returns (uint256) {
return baseMiningReward;
}
/**
* Helper method to check a nonce
* @param nonce The nonce to check
* @param challengeDigest the digest to check
* @param challengeNumber to check
* @return digesttest The resulting digest
*/
// solhint-disable-next-line
function getMintDigest(uint256 nonce, bytes32 challengeDigest, bytes32 challengeNumber) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
return digest;
}
/**
* Helper method to check if a nonce meets the difficulty
* @param nonce The nonce to check
* @param challengeDigest the digest to check
* @param challengeNumber the challenge number to check
* @param testTarget the difficulty to check
* @return success Boolean indicating success
*/
function checkMintSolution(uint256 nonce, bytes32 challengeDigest, bytes32 challengeNumber, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
if (uint256(digest) > testTarget) revert();
return (digest == challengeDigest);
}
/**
* Internal function to check a hash
* @param nonce The nonce to check
* @param challengeDigest it should create
* @return digest The digest created
*/
function _hash(uint256 nonce, bytes32 challengeDigest) internal returns (bytes32 digest) {
digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
//the challenge digest must match the expected
if (digest != challengeDigest) revert();
//the digest must be smaller than the target
if (uint256(digest) > difficulty) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if (solution != 0x0) revert(); //prevent the same answer from awarding twice
}
/**
* Reward a miner Pep tokens
* @param nonce Nonce to use as seed for Pepe dna creation
* @return The amount of PEP tokens rewarded
*/
function _reward(uint256 nonce) internal returns (uint) {
uint reward_amount = getMiningReward();
pepToken.transfer(msg.sender, reward_amount);
if (epochCount % 16 == 0) { //every 16th block reward a pepe
if (pepeGrinder.dusting(msg.sender)) { //if miner is pool mining send it through the grinder
uint256 newPepe = pepeContract.minePepe(nonce, address(pepeGrinder));
pepeGrinder.dustPepe(newPepe, msg.sender);
} else {
pepeContract.minePepe(nonce, msg.sender);
}
//every 16th block send part of the block reward
pepToken.transfer(beneficiary, reward_amount);
}
return reward_amount;
}
/**
* Internal method to readjust difficulty
* @return The new difficulty
*/
function _adjustDifficulty() internal returns (uint) {
//every so often, readjust difficulty. Dont readjust when deploying
if (epochCount % blocksPerReadjustment != 0) {
return difficulty;
}
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 360 ethereum blocks per hour
//we want miners to spend 8 minutes to mine each 'block', about 31 ethereum blocks = one CryptoPepes block
uint epochsMined = blocksPerReadjustment;
uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR;
//if there were less eth blocks passed in time than expected
if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) {
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod);
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); //by up to 50 %
} else {
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod);
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); //always between 0 and 1000
//make it easier
difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if (difficulty < _MINIMUM_TARGET) { //very dificult
difficulty = _MINIMUM_TARGET;
}
if (difficulty > _MAXIMUM_TARGET) { //very easy
difficulty = _MAXIMUM_TARGET;
}
return difficulty;
}
}
|
Get approved address for a token _tokenId Token ID to get the approved address for return The address that is approved for this token/
|
function getApproved(uint256 _tokenId) external view returns (address) {
return approved[_tokenId];
}
| 5,781,156 |
pragma solidity 0.5.8;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./Wallet.sol";
import "./VestingEscrowWalletStorage.sol";
/**
* @title Wallet for core vesting escrow functionality
*/
contract VestingEscrowWallet is VestingEscrowWalletStorage, Wallet {
using SafeMath for uint256;
// States used to represent the status of the schedule
enum State {CREATED, STARTED, COMPLETED}
// Emit when new schedule is added
event AddSchedule(
address indexed _beneficiary,
bytes32 _templateName,
uint256 _startTime
);
// Emit when schedule is modified
event ModifySchedule(
address indexed _beneficiary,
bytes32 _templateName,
uint256 _startTime
);
// Emit when all schedules are revoked for user
event RevokeAllSchedules(address indexed _beneficiary);
// Emit when schedule is revoked
event RevokeSchedule(address indexed _beneficiary, bytes32 _templateName);
// Emit when tokes are deposited to wallet
event DepositTokens(uint256 _numberOfTokens, address _sender);
// Emit when all unassigned tokens are sent to treasury
event SendToTreasury(uint256 _numberOfTokens, address _sender);
// Emit when is sent tokes to user
event SendTokens(address indexed _beneficiary, uint256 _numberOfTokens);
// Emit when template is added
event AddTemplate(bytes32 _name, uint256 _numberOfTokens, uint256 _duration, uint256 _frequency);
// Emit when template is removed
event RemoveTemplate(bytes32 _name);
// Emit when the treasury wallet gets changed
event TreasuryWalletChanged(address _newWallet, address _oldWallet);
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress)
public
Module(_securityToken, _polyAddress)
{
}
/**
* @notice This function returns the signature of the configure function
*/
function getInitFunction() public pure returns (bytes4) {
return this.configure.selector;
}
/**
* @notice Used to initialize the treasury wallet address
* @param _treasuryWallet Address of the treasury wallet
*/
function configure(address _treasuryWallet) public onlyFactory {
_setWallet(_treasuryWallet);
}
/**
* @notice Used to change the treasury wallet address
* @param _newTreasuryWallet Address of the treasury wallet
*/
function changeTreasuryWallet(address _newTreasuryWallet) public {
_onlySecurityTokenOwner();
_setWallet(_newTreasuryWallet);
}
function _setWallet(address _newTreasuryWallet) internal {
emit TreasuryWalletChanged(_newTreasuryWallet, treasuryWallet);
treasuryWallet = _newTreasuryWallet;
}
/**
* @notice Used to deposit tokens from treasury wallet to the vesting escrow wallet
* @param _numberOfTokens Number of tokens that should be deposited
*/
function depositTokens(uint256 _numberOfTokens) external withPerm(ADMIN) {
_depositTokens(_numberOfTokens);
}
function _depositTokens(uint256 _numberOfTokens) internal {
require(_numberOfTokens > 0, "Should be > 0");
require(
securityToken.transferFrom(msg.sender, address(this), _numberOfTokens),
"Failed transferFrom"
);
unassignedTokens = unassignedTokens.add(_numberOfTokens);
emit DepositTokens(_numberOfTokens, msg.sender);
}
/**
* @notice Sends unassigned tokens to the treasury wallet
* @param _amount Amount of tokens that should be send to the treasury wallet
*/
function sendToTreasury(uint256 _amount) public withPerm(OPERATOR) {
require(_amount > 0, "Amount cannot be zero");
require(_amount <= unassignedTokens, "Amount is greater than unassigned tokens");
unassignedTokens = unassignedTokens - _amount;
require(securityToken.transfer(getTreasuryWallet(), _amount), "Transfer failed");
emit SendToTreasury(_amount, msg.sender);
}
/**
* @notice Returns the treasury wallet address
*/
function getTreasuryWallet() public view returns(address) {
if (treasuryWallet == address(0)) {
address wallet = IDataStore(getDataStore()).getAddress(TREASURY);
require(wallet != address(0), "Invalid address");
return wallet;
} else
return treasuryWallet;
}
/**
* @notice Pushes available tokens to the beneficiary's address
* @param _beneficiary Address of the beneficiary who will receive tokens
*/
function pushAvailableTokens(address _beneficiary) public withPerm(OPERATOR) {
_sendTokens(_beneficiary);
}
/**
* @notice Used to withdraw available tokens by beneficiary
*/
function pullAvailableTokens() external whenNotPaused {
_sendTokens(msg.sender);
}
/**
* @notice Adds template that can be used for creating schedule
* @param _name Name of the template will be created
* @param _numberOfTokens Number of tokens that should be assigned to schedule
* @param _duration Duration of the vesting schedule
* @param _frequency Frequency of the vesting schedule
*/
function addTemplate(bytes32 _name, uint256 _numberOfTokens, uint256 _duration, uint256 _frequency) external withPerm(ADMIN) {
_addTemplate(_name, _numberOfTokens, _duration, _frequency);
}
function _addTemplate(bytes32 _name, uint256 _numberOfTokens, uint256 _duration, uint256 _frequency) internal {
require(_name != bytes32(0), "Invalid name");
require(!_isTemplateExists(_name), "Already exists");
_validateTemplate(_numberOfTokens, _duration, _frequency);
templateNames.push(_name);
templates[_name] = Template(_numberOfTokens, _duration, _frequency, templateNames.length - 1);
emit AddTemplate(_name, _numberOfTokens, _duration, _frequency);
}
/**
* @notice Removes template with a given name
* @param _name Name of the template that will be removed
*/
function removeTemplate(bytes32 _name) external withPerm(ADMIN) {
require(_isTemplateExists(_name), "Template not found");
require(templateToUsers[_name].length == 0, "Template is used");
uint256 index = templates[_name].index;
if (index != templateNames.length - 1) {
templateNames[index] = templateNames[templateNames.length - 1];
templates[templateNames[index]].index = index;
}
templateNames.length--;
// delete template data
delete templates[_name];
emit RemoveTemplate(_name);
}
/**
* @notice Returns count of the templates those can be used for creating schedule
* @return Count of the templates
*/
function getTemplateCount() external view returns(uint256) {
return templateNames.length;
}
/**
* @notice Gets the list of the template names those can be used for creating schedule
* @return bytes32 Array of all template names were created
*/
function getAllTemplateNames() external view returns(bytes32[] memory) {
return templateNames;
}
/**
* @notice Adds vesting schedules for each of the beneficiary's address
* @param _beneficiary Address of the beneficiary for whom it is scheduled
* @param _templateName Name of the template that will be created
* @param _numberOfTokens Total number of tokens for created schedule
* @param _duration Duration of the created vesting schedule
* @param _frequency Frequency of the created vesting schedule
* @param _startTime Start time of the created vesting schedule
*/
function addSchedule(
address _beneficiary,
bytes32 _templateName,
uint256 _numberOfTokens,
uint256 _duration,
uint256 _frequency,
uint256 _startTime
)
external
withPerm(ADMIN)
{
_addSchedule(_beneficiary, _templateName, _numberOfTokens, _duration, _frequency, _startTime);
}
function _addSchedule(
address _beneficiary,
bytes32 _templateName,
uint256 _numberOfTokens,
uint256 _duration,
uint256 _frequency,
uint256 _startTime
)
internal
{
_addTemplate(_templateName, _numberOfTokens, _duration, _frequency);
_addScheduleFromTemplate(_beneficiary, _templateName, _startTime);
}
/**
* @notice Adds vesting schedules from template for the beneficiary
* @param _beneficiary Address of the beneficiary for whom it is scheduled
* @param _templateName Name of the exists template
* @param _startTime Start time of the created vesting schedule
*/
function addScheduleFromTemplate(address _beneficiary, bytes32 _templateName, uint256 _startTime) external withPerm(ADMIN) {
_addScheduleFromTemplate(_beneficiary, _templateName, _startTime);
}
function _addScheduleFromTemplate(address _beneficiary, bytes32 _templateName, uint256 _startTime) internal {
require(_beneficiary != address(0), "Invalid address");
require(_isTemplateExists(_templateName), "Template not found");
uint256 index = userToTemplateIndex[_beneficiary][_templateName];
require(
schedules[_beneficiary].length == 0 ||
schedules[_beneficiary][index].templateName != _templateName,
"Already added"
);
require(_startTime >= now, "Date in the past");
uint256 numberOfTokens = templates[_templateName].numberOfTokens;
if (numberOfTokens > unassignedTokens) {
_depositTokens(numberOfTokens.sub(unassignedTokens));
}
unassignedTokens = unassignedTokens.sub(numberOfTokens);
if (!beneficiaryAdded[_beneficiary]) {
beneficiaries.push(_beneficiary);
beneficiaryAdded[_beneficiary] = true;
}
schedules[_beneficiary].push(Schedule(_templateName, 0, _startTime));
userToTemplates[_beneficiary].push(_templateName);
userToTemplateIndex[_beneficiary][_templateName] = schedules[_beneficiary].length - 1;
templateToUsers[_templateName].push(_beneficiary);
templateToUserIndex[_templateName][_beneficiary] = templateToUsers[_templateName].length - 1;
emit AddSchedule(_beneficiary, _templateName, _startTime);
}
/**
* @notice Modifies vesting schedules for each of the beneficiary
* @param _beneficiary Address of the beneficiary for whom it is modified
* @param _templateName Name of the template was used for schedule creation
* @param _startTime Start time of the created vesting schedule
*/
function modifySchedule(address _beneficiary, bytes32 _templateName, uint256 _startTime) external withPerm(ADMIN) {
_modifySchedule(_beneficiary, _templateName, _startTime);
}
function _modifySchedule(address _beneficiary, bytes32 _templateName, uint256 _startTime) internal {
_checkSchedule(_beneficiary, _templateName);
require(_startTime > now, "Date in the past");
uint256 index = userToTemplateIndex[_beneficiary][_templateName];
Schedule storage schedule = schedules[_beneficiary][index];
/*solium-disable-next-line security/no-block-members*/
require(now < schedule.startTime, "Schedule started");
schedule.startTime = _startTime;
emit ModifySchedule(_beneficiary, _templateName, _startTime);
}
/**
* @notice Revokes vesting schedule with given template name for given beneficiary
* @param _beneficiary Address of the beneficiary for whom it is revoked
* @param _templateName Name of the template was used for schedule creation
*/
function revokeSchedule(address _beneficiary, bytes32 _templateName) external withPerm(ADMIN) {
_checkSchedule(_beneficiary, _templateName);
uint256 index = userToTemplateIndex[_beneficiary][_templateName];
_sendTokensPerSchedule(_beneficiary, index);
uint256 releasedTokens = _getReleasedTokens(_beneficiary, index);
unassignedTokens = unassignedTokens.add(templates[_templateName].numberOfTokens.sub(releasedTokens));
_deleteUserToTemplates(_beneficiary, _templateName);
_deleteTemplateToUsers(_beneficiary, _templateName);
emit RevokeSchedule(_beneficiary, _templateName);
}
function _deleteUserToTemplates(address _beneficiary, bytes32 _templateName) internal {
uint256 index = userToTemplateIndex[_beneficiary][_templateName];
Schedule[] storage userSchedules = schedules[_beneficiary];
if (index != userSchedules.length - 1) {
userSchedules[index] = userSchedules[userSchedules.length - 1];
userToTemplates[_beneficiary][index] = userToTemplates[_beneficiary][userToTemplates[_beneficiary].length - 1];
userToTemplateIndex[_beneficiary][userSchedules[index].templateName] = index;
}
userSchedules.length--;
userToTemplates[_beneficiary].length--;
delete userToTemplateIndex[_beneficiary][_templateName];
}
function _deleteTemplateToUsers(address _beneficiary, bytes32 _templateName) internal {
uint256 templateIndex = templateToUserIndex[_templateName][_beneficiary];
if (templateIndex != templateToUsers[_templateName].length - 1) {
templateToUsers[_templateName][templateIndex] = templateToUsers[_templateName][templateToUsers[_templateName].length - 1];
templateToUserIndex[_templateName][templateToUsers[_templateName][templateIndex]] = templateIndex;
}
templateToUsers[_templateName].length--;
delete templateToUserIndex[_templateName][_beneficiary];
}
/**
* @notice Revokes all vesting schedules for given beneficiary's address
* @param _beneficiary Address of the beneficiary for whom all schedules will be revoked
*/
function revokeAllSchedules(address _beneficiary) public withPerm(ADMIN) {
_revokeAllSchedules(_beneficiary);
}
function _revokeAllSchedules(address _beneficiary) internal {
require(_beneficiary != address(0), "Invalid address");
_sendTokens(_beneficiary);
Schedule[] storage userSchedules = schedules[_beneficiary];
for (uint256 i = 0; i < userSchedules.length; i++) {
uint256 releasedTokens = _getReleasedTokens(_beneficiary, i);
Template memory template = templates[userSchedules[i].templateName];
unassignedTokens = unassignedTokens.add(template.numberOfTokens.sub(releasedTokens));
delete userToTemplateIndex[_beneficiary][userSchedules[i].templateName];
_deleteTemplateToUsers(_beneficiary, userSchedules[i].templateName);
}
delete schedules[_beneficiary];
delete userToTemplates[_beneficiary];
emit RevokeAllSchedules(_beneficiary);
}
/**
* @notice Returns beneficiary's schedule created using template name
* @param _beneficiary Address of the beneficiary who will receive tokens
* @param _templateName Name of the template was used for schedule creation
* @return beneficiary's schedule data (numberOfTokens, duration, frequency, startTime, claimedTokens, State)
*/
function getSchedule(address _beneficiary, bytes32 _templateName) external view returns(uint256, uint256, uint256, uint256, uint256, State) {
_checkSchedule(_beneficiary, _templateName);
uint256 index = userToTemplateIndex[_beneficiary][_templateName];
Schedule memory schedule = schedules[_beneficiary][index];
return (
templates[schedule.templateName].numberOfTokens,
templates[schedule.templateName].duration,
templates[schedule.templateName].frequency,
schedule.startTime,
schedule.claimedTokens,
_getScheduleState(_beneficiary, _templateName)
);
}
function _getScheduleState(address _beneficiary, bytes32 _templateName) internal view returns(State) {
_checkSchedule(_beneficiary, _templateName);
uint256 index = userToTemplateIndex[_beneficiary][_templateName];
Schedule memory schedule = schedules[_beneficiary][index];
if (now < schedule.startTime) {
return State.CREATED;
} else if (now > schedule.startTime && now < schedule.startTime.add(templates[_templateName].duration)) {
return State.STARTED;
} else {
return State.COMPLETED;
}
}
/**
* @notice Returns list of the template names for given beneficiary's address
* @param _beneficiary Address of the beneficiary
* @return List of the template names that were used for schedule creation
*/
function getTemplateNames(address _beneficiary) external view returns(bytes32[] memory) {
require(_beneficiary != address(0), "Invalid address");
return userToTemplates[_beneficiary];
}
/**
* @notice Returns count of the schedules were created for given beneficiary
* @param _beneficiary Address of the beneficiary
* @return Count of beneficiary's schedules
*/
function getScheduleCount(address _beneficiary) external view returns(uint256) {
require(_beneficiary != address(0), "Invalid address");
return schedules[_beneficiary].length;
}
function _getAvailableTokens(address _beneficiary, uint256 _index) internal view returns(uint256) {
Schedule memory schedule = schedules[_beneficiary][_index];
uint256 releasedTokens = _getReleasedTokens(_beneficiary, _index);
return releasedTokens.sub(schedule.claimedTokens);
}
function _getReleasedTokens(address _beneficiary, uint256 _index) internal view returns(uint256) {
Schedule memory schedule = schedules[_beneficiary][_index];
Template memory template = templates[schedule.templateName];
/*solium-disable-next-line security/no-block-members*/
if (now > schedule.startTime) {
uint256 periodCount = template.duration.div(template.frequency);
/*solium-disable-next-line security/no-block-members*/
uint256 periodNumber = (now.sub(schedule.startTime)).div(template.frequency);
if (periodNumber > periodCount) {
periodNumber = periodCount;
}
return template.numberOfTokens.mul(periodNumber).div(periodCount);
} else {
return 0;
}
}
/**
* @notice Used to bulk send available tokens for each of the beneficiaries
* @param _fromIndex Start index of array of beneficiary's addresses
* @param _toIndex End index of array of beneficiary's addresses
*/
function pushAvailableTokensMulti(uint256 _fromIndex, uint256 _toIndex) public withPerm(OPERATOR) {
require(_toIndex < beneficiaries.length, "Array out of bound");
for (uint256 i = _fromIndex; i <= _toIndex; i++) {
if (schedules[beneficiaries[i]].length !=0)
pushAvailableTokens(beneficiaries[i]);
}
}
/**
* @notice Used to bulk add vesting schedules for each of beneficiary
* @param _beneficiaries Array of the beneficiary's addresses
* @param _templateNames Array of the template names
* @param _numberOfTokens Array of number of tokens should be assigned to schedules
* @param _durations Array of the vesting duration
* @param _frequencies Array of the vesting frequency
* @param _startTimes Array of the vesting start time
*/
function addScheduleMulti(
address[] memory _beneficiaries,
bytes32[] memory _templateNames,
uint256[] memory _numberOfTokens,
uint256[] memory _durations,
uint256[] memory _frequencies,
uint256[] memory _startTimes
)
public
withPerm(ADMIN)
{
require(
_beneficiaries.length == _templateNames.length && /*solium-disable-line operator-whitespace*/
_beneficiaries.length == _numberOfTokens.length && /*solium-disable-line operator-whitespace*/
_beneficiaries.length == _durations.length && /*solium-disable-line operator-whitespace*/
_beneficiaries.length == _frequencies.length && /*solium-disable-line operator-whitespace*/
_beneficiaries.length == _startTimes.length,
"Arrays sizes mismatch"
);
for (uint256 i = 0; i < _beneficiaries.length; i++) {
_addSchedule(_beneficiaries[i], _templateNames[i], _numberOfTokens[i], _durations[i], _frequencies[i], _startTimes[i]);
}
}
/**
* @notice Used to bulk add vesting schedules from template for each of the beneficiary
* @param _beneficiaries Array of beneficiary's addresses
* @param _templateNames Array of the template names were used for schedule creation
* @param _startTimes Array of the vesting start time
*/
function addScheduleFromTemplateMulti(
address[] memory _beneficiaries,
bytes32[] memory _templateNames,
uint256[] memory _startTimes
)
public
withPerm(ADMIN)
{
require(_beneficiaries.length == _templateNames.length && _beneficiaries.length == _startTimes.length, "Arrays sizes mismatch");
for (uint256 i = 0; i < _beneficiaries.length; i++) {
_addScheduleFromTemplate(_beneficiaries[i], _templateNames[i], _startTimes[i]);
}
}
/**
* @notice Used to bulk revoke vesting schedules for each of the beneficiaries
* @param _beneficiaries Array of the beneficiary's addresses
*/
function revokeSchedulesMulti(address[] memory _beneficiaries) public withPerm(ADMIN) {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
_revokeAllSchedules(_beneficiaries[i]);
}
}
/**
* @notice Used to bulk modify vesting schedules for each of the beneficiaries
* @param _beneficiaries Array of the beneficiary's addresses
* @param _templateNames Array of the template names
* @param _startTimes Array of the vesting start time
*/
function modifyScheduleMulti(
address[] memory _beneficiaries,
bytes32[] memory _templateNames,
uint256[] memory _startTimes
)
public
withPerm(ADMIN)
{
require(
_beneficiaries.length == _templateNames.length && /*solium-disable-line operator-whitespace*/
_beneficiaries.length == _startTimes.length,
"Arrays sizes mismatch"
);
for (uint256 i = 0; i < _beneficiaries.length; i++) {
_modifySchedule(_beneficiaries[i], _templateNames[i], _startTimes[i]);
}
}
function _checkSchedule(address _beneficiary, bytes32 _templateName) internal view {
require(_beneficiary != address(0), "Invalid address");
uint256 index = userToTemplateIndex[_beneficiary][_templateName];
require(
index < schedules[_beneficiary].length &&
schedules[_beneficiary][index].templateName == _templateName,
"Schedule not found"
);
}
function _isTemplateExists(bytes32 _name) internal view returns(bool) {
return templates[_name].numberOfTokens > 0;
}
function _validateTemplate(uint256 _numberOfTokens, uint256 _duration, uint256 _frequency) internal view {
require(_numberOfTokens > 0, "Zero amount");
require(_duration % _frequency == 0, "Invalid frequency");
uint256 periodCount = _duration.div(_frequency);
require(_numberOfTokens % periodCount == 0);
uint256 amountPerPeriod = _numberOfTokens.div(periodCount);
require(amountPerPeriod % securityToken.granularity() == 0, "Invalid granularity");
}
function _sendTokens(address _beneficiary) internal {
for (uint256 i = 0; i < schedules[_beneficiary].length; i++) {
_sendTokensPerSchedule(_beneficiary, i);
}
}
function _sendTokensPerSchedule(address _beneficiary, uint256 _index) internal {
uint256 amount = _getAvailableTokens(_beneficiary, _index);
if (amount > 0) {
schedules[_beneficiary][_index].claimedTokens = schedules[_beneficiary][_index].claimedTokens.add(amount);
require(securityToken.transfer(_beneficiary, amount), "Transfer failed");
emit SendTokens(_beneficiary, amount);
}
}
/**
* @notice Return the permissions flag that are associated with VestingEscrowWallet
*/
function getPermissions() public view returns(bytes32[] memory) {
bytes32[] memory allPermissions = new bytes32[](2);
allPermissions[0] = ADMIN;
allPermissions[1] = OPERATOR;
return allPermissions;
}
}
|
Revokes vesting schedule with given template name for given beneficiary _beneficiary Address of the beneficiary for whom it is revoked _templateName Name of the template was used for schedule creation/
|
function revokeSchedule(address _beneficiary, bytes32 _templateName) external withPerm(ADMIN) {
_checkSchedule(_beneficiary, _templateName);
uint256 index = userToTemplateIndex[_beneficiary][_templateName];
_sendTokensPerSchedule(_beneficiary, index);
uint256 releasedTokens = _getReleasedTokens(_beneficiary, index);
unassignedTokens = unassignedTokens.add(templates[_templateName].numberOfTokens.sub(releasedTokens));
_deleteUserToTemplates(_beneficiary, _templateName);
_deleteTemplateToUsers(_beneficiary, _templateName);
emit RevokeSchedule(_beneficiary, _templateName);
}
| 1,805,491 |
pragma solidity ^0.5.2;
pragma experimental ABIEncoderV2;
import "../libs/SafeMath.sol";
import "../libs/SafeERC20.sol";
import "../libs/SignatureValidator.sol";
import "../AdExCore.sol";
contract Identity {
using SafeMath for uint;
// Constants
bytes4 private CHANNEL_WITHDRAW_SELECTOR = AdExCore(0x0).channelWithdraw.selector;
bytes4 private CHANNEL_WITHDRAW_EXPIRED_SELECTOR = AdExCore(0x0).channelWithdrawExpired.selector;
// The next allowed nonce
uint public nonce = 0;
mapping (address => uint8) public privileges;
// Routine operations are authorized at once for a period, fee is paid once
mapping (bytes32 => bool) public routinePaidFees;
enum PrivilegeLevel {
None,
Routines,
Transactions,
Withdraw
}
// Events
event LogPrivilegeChanged(address indexed addr, uint8 privLevel);
// Transaction structure
// Those can be executed by keys with >= PrivilegeLevel.Transactions
// Even though the contract cannot receive ETH, we are able to send ETH (.value), cause ETH might've been sent to the contract address before it's deployed
struct Transaction {
// replay protection
address identityContract;
uint nonce;
// tx fee, in tokens
address feeTokenAddr;
uint feeTokenAmount;
// all the regular txn data
address to;
uint value;
bytes data;
}
// RoutineAuthorizations allow the user to authorize (via keys >= PrivilegeLevel.Routines) a particular relayer to do any number of routines
// those routines are safe: e.g. withdrawing channels to the identity, or from the identity to the pre-approved withdraw (>= PrivilegeLevel.Withdraw) address
// while the fee will be paid only ONCE per auth, the authorization can be used until validUntil
// while the routines are safe, there is some level of implied trust as the relayer may run executeRoutines without any routines to claim the fee
struct RoutineAuthorization {
address identityContract;
address relayer;
address outpace;
uint validUntil;
address feeTokenAddr;
uint feeTokenAmount;
}
struct RoutineOperation {
uint mode;
bytes data;
}
constructor(address addr, uint8 privLevel, address feeTokenAddr, address feeBeneficiery, uint feeTokenAmount)
public
{
privileges[addr] = privLevel;
emit LogPrivilegeChanged(addr, privLevel);
if (feeTokenAmount > 0) {
SafeERC20.transfer(feeTokenAddr, feeBeneficiery, feeTokenAmount);
}
}
function setAddrPrivilege(address addr, uint8 privLevel)
external
{
require(msg.sender == address(this), 'ONLY_IDENTITY_CAN_CALL');
// @TODO: should we have on-chain anti-bricking guarantees? maybe there's an easy way to do this
// since this can only be invoked by PrivilegeLevels.Transaction, maybe if we make sure we can't invoke setAddrPrivilege(addr, level) where addr == signer, it may be sufficient
privileges[addr] = privLevel;
emit LogPrivilegeChanged(addr, privLevel);
}
function execute(Transaction[] memory txns, bytes32[3][] memory signatures)
public
{
address feeTokenAddr = txns[0].feeTokenAddr;
uint feeTokenAmount = 0;
for (uint i=0; i<txns.length; i++) {
Transaction memory txn = txns[i];
require(txn.identityContract == address(this), 'TRANSACTION_NOT_FOR_CONTRACT');
require(txn.feeTokenAddr == feeTokenAddr, 'EXECUTE_NEEDS_SINGLE_TOKEN');
require(txn.nonce == nonce, 'WRONG_NONCE');
// If we use the naive abi.encode(txn) and have a field of type `bytes`,
// there is a discrepancy between ethereumjs-abi and solidity
// if we enter every field individually, in order, there is no discrepancy
//bytes32 hash = keccak256(abi.encode(txn));
bytes32 hash = keccak256(abi.encode(txn.identityContract, txn.nonce, txn.feeTokenAddr, txn.feeTokenAmount, txn.to, txn.value, txn.data));
address signer = SignatureValidator.recoverAddr(hash, signatures[i]);
require(privileges[signer] >= uint8(PrivilegeLevel.Transactions), 'INSUFFICIENT_PRIVILEGE');
nonce = nonce.add(1);
feeTokenAmount = feeTokenAmount.add(txn.feeTokenAmount);
require(executeCall(txn.to, txn.value, txn.data), 'CALL_FAILED');
}
if (feeTokenAmount > 0) {
SafeERC20.transfer(feeTokenAddr, msg.sender, feeTokenAmount);
}
}
function executeRoutines(RoutineAuthorization memory auth, bytes32[3] memory signature, RoutineOperation[] memory operations)
public
{
require(auth.identityContract == address(this), 'AUTHORIZATION_NOT_FOR_CONTRACT');
require(auth.relayer == msg.sender, 'ONLY_RELAYER_CAN_CALL');
require(auth.validUntil >= now, 'AUTHORIZATION_EXPIRED');
bytes32 hash = keccak256(abi.encode(auth));
address signer = SignatureValidator.recoverAddr(hash, signature);
require(privileges[signer] >= uint8(PrivilegeLevel.Routines), 'INSUFFICIENT_PRIVILEGE');
for (uint i=0; i<operations.length; i++) {
RoutineOperation memory op = operations[i];
// @TODO: is it possible to preserve original error from the call
if (op.mode == 0) {
// Channel: Withdraw
bool success = executeCall(auth.outpace, 0, abi.encodePacked(CHANNEL_WITHDRAW_SELECTOR, op.data));
require(success, 'WITHDRAW_FAILED');
} else if (op.mode == 1) {
// Channel: Withdraw Expired
bool success = executeCall(auth.outpace, 0, abi.encodePacked(CHANNEL_WITHDRAW_EXPIRED_SELECTOR, op.data));
require(success, 'WITHDRAW_EXPIRED_FAILED');
} else if (op.mode == 2) {
// Withdraw from identity
(address tokenAddr, address to, uint amount) = abi.decode(op.data, (address, address, uint));
require(privileges[to] >= uint8(PrivilegeLevel.Withdraw), 'INSUFFICIENT_PRIVILEGE_WITHDRAW');
SafeERC20.transfer(tokenAddr, to, amount);
} else {
require(false, 'INVALID_MODE');
}
}
if (!routinePaidFees[hash] && auth.feeTokenAmount > 0) {
routinePaidFees[hash] = true;
SafeERC20.transfer(auth.feeTokenAddr, msg.sender, auth.feeTokenAmount);
}
}
// we shouldn't use address.call(), cause: https://github.com/ethereum/solidity/issues/2884
// copied from https://github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol
// there's also
// https://github.com/gnosis/MultiSigWallet/commit/e1b25e8632ca28e9e9e09c81bd20bf33fdb405ce
// https://github.com/austintgriffith/bouncer-proxy/blob/master/BouncerProxy/BouncerProxy.sol
// https://github.com/gnosis/safe-contracts/blob/7e2eeb3328bb2ae85c36bc11ea6afc14baeb663c/contracts/base/Executor.sol
function executeCall(address to, uint256 value, bytes memory data)
internal
returns (bool success)
{
assembly {
success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
}
|
If we use the naive abi.encode(txn) and have a field of type `bytes`, there is a discrepancy between ethereumjs-abi and solidity if we enter every field individually, in order, there is no discrepancybytes32 hash = keccak256(abi.encode(txn));
|
function execute(Transaction[] memory txns, bytes32[3][] memory signatures)
public
{
address feeTokenAddr = txns[0].feeTokenAddr;
uint feeTokenAmount = 0;
for (uint i=0; i<txns.length; i++) {
Transaction memory txn = txns[i];
require(txn.identityContract == address(this), 'TRANSACTION_NOT_FOR_CONTRACT');
require(txn.feeTokenAddr == feeTokenAddr, 'EXECUTE_NEEDS_SINGLE_TOKEN');
require(txn.nonce == nonce, 'WRONG_NONCE');
bytes32 hash = keccak256(abi.encode(txn.identityContract, txn.nonce, txn.feeTokenAddr, txn.feeTokenAmount, txn.to, txn.value, txn.data));
address signer = SignatureValidator.recoverAddr(hash, signatures[i]);
require(privileges[signer] >= uint8(PrivilegeLevel.Transactions), 'INSUFFICIENT_PRIVILEGE');
nonce = nonce.add(1);
feeTokenAmount = feeTokenAmount.add(txn.feeTokenAmount);
require(executeCall(txn.to, txn.value, txn.data), 'CALL_FAILED');
}
if (feeTokenAmount > 0) {
SafeERC20.transfer(feeTokenAddr, msg.sender, feeTokenAmount);
}
}
| 2,472,677 |
pragma solidity ^0.4.23;
import "../registry/contracts/HasRegistry.sol";
import "./modularERC20/ModularPausableToken.sol";
contract CompliantToken is ModularPausableToken, HasRegistry {
// In order to deposit USD and receive newly minted TrueUSD, or to burn TrueUSD to
// redeem it for USD, users must first go through a KYC/AML check (which includes proving they
// control their ethereum address using AddressValidation.sol).
string constant HAS_PASSED_KYC_AML = "hasPassedKYC/AML";
// Redeeming ("burning") TrueUSD tokens for USD requires a separate flag since
// users must not only be KYC/AML'ed but must also have bank information on file.
string constant CAN_BURN = "canBurn";
// Addresses can also be blacklisted, preventing them from sending or receiving
// TrueUSD. This can be used to prevent the use of TrueUSD by bad actors in
// accordance with law enforcement. See [TrueCoin Terms of Use](https://www.trusttoken.com/trueusd/terms-of-use)
string constant IS_BLACKLISTED = "isBlacklisted";
// Only KYC/AML'ed accounts can interact with addresses affiliated with a
// restricted exchange.
string constant IS_RESTRICTED_EXCHANGE = "isRestrictedExchange";
event WipeBlacklistedAccount(address indexed account, uint256 balance);
function burnAllArgs(address _burner, uint256 _value, string _note) internal {
require(registry.hasAttribute(_burner, CAN_BURN),"_burner does not have canBurn attribute");
require(!registry.hasAttribute(_burner, IS_BLACKLISTED),"_burner is blacklisted");
super.burnAllArgs(_burner, _value, _note);
}
function mint(address _to, uint256 _value) internal returns (bool) {
require(registry.hasAttribute(_to, HAS_PASSED_KYC_AML),"_to has not passed kyc");
require(!registry.hasAttribute(_to, IS_BLACKLISTED),"_to is blacklisted");
super.mint(_to, _value);
}
// A blacklisted address can't call transferFrom
function transferFromAllArgs(address _from, address _to, uint256 _value, address _spender) internal {
require(!registry.hasAttribute(_spender, IS_BLACKLISTED),"_spender is blacklisted");
require(!registry.hasAttribute(_spender, IS_RESTRICTED_EXCHANGE) || (registry.hasAttribute(_from, HAS_PASSED_KYC_AML) && registry.hasAttribute(_to, HAS_PASSED_KYC_AML)),
"_spender is restricted exchange and _from has no kyc, or _to has no kyc");
require((!registry.hasAttribute(_to, IS_RESTRICTED_EXCHANGE) && !registry.hasAttribute(_from, IS_RESTRICTED_EXCHANGE)) || registry.hasAttribute(_spender, HAS_PASSED_KYC_AML),
"_spender is restricted exchange or _from is restricted exchange, or _spender has no kyc");
super.transferFromAllArgs(_from, _to, _value, _spender);
}
// transfer and transferFrom both call this function, so check blacklist here.
function transferAllArgs(address _from, address _to, uint256 _value) internal {
require(!registry.hasAttribute(_from, IS_BLACKLISTED),"_from is blacklisted");
require(!registry.hasAttribute(_to, IS_BLACKLISTED),"_to is blacklisted");
require(!registry.hasAttribute(_to, IS_RESTRICTED_EXCHANGE) || registry.hasAttribute(_from, HAS_PASSED_KYC_AML),
"registry is restricted exchange and _from has no kyc");
require(!registry.hasAttribute(_from, IS_RESTRICTED_EXCHANGE) || registry.hasAttribute(_to, HAS_PASSED_KYC_AML),
"registry is restricted exchange and _to has no kyc");
super.transferAllArgs(_from, _to, _value);
}
// Destroy the tokens owned by a blacklisted account
function wipeBlacklistedAccount(address _account) public onlyOwner {
require(registry.hasAttribute(_account, IS_BLACKLISTED),"_account is not blacklisted");
uint256 oldValue = balanceOf(_account);
balances.setBalance(_account, 0);
totalSupply_ = totalSupply_.sub(oldValue);
emit WipeBlacklistedAccount(_account, oldValue);
}
}
|
transfer and transferFrom both call this function, so check blacklist here.
|
function transferAllArgs(address _from, address _to, uint256 _value) internal {
require(!registry.hasAttribute(_from, IS_BLACKLISTED),"_from is blacklisted");
require(!registry.hasAttribute(_to, IS_BLACKLISTED),"_to is blacklisted");
require(!registry.hasAttribute(_to, IS_RESTRICTED_EXCHANGE) || registry.hasAttribute(_from, HAS_PASSED_KYC_AML),
"registry is restricted exchange and _from has no kyc");
require(!registry.hasAttribute(_from, IS_RESTRICTED_EXCHANGE) || registry.hasAttribute(_to, HAS_PASSED_KYC_AML),
"registry is restricted exchange and _to has no kyc");
super.transferAllArgs(_from, _to, _value);
}
| 13,125,058 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "./libraries/ECDSAOffsetRecovery.sol";
import "./libraries/FullMath.sol";
/// @title Swap contract for multisignature bridge
contract SwapContract is AccessControl, Pausable, ECDSAOffsetRecovery {
using SafeERC20 for IERC20;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE");
uint128 public immutable numOfThisBlockchain;
IUniswapV2Router02 public blockchainRouter;
address public blockchainPool;
mapping(uint256 => address) public RubicAddresses;
mapping(uint256 => bool) public existingOtherBlockchain;
mapping(uint256 => uint256) public feeAmountOfBlockchain;
mapping(uint256 => uint256) public blockchainCryptoFee;
uint256 public constant SIGNATURE_LENGTH = 65;
struct processedTx {
uint256 statusCode;
bytes32 hashedParams;
}
mapping(bytes32 => processedTx) public processedTransactions;
uint256 public minConfirmationSignatures = 3;
uint256 public minTokenAmount;
uint256 public maxTokenAmount;
uint256 public maxGasPrice;
uint256 public minConfirmationBlocks;
uint256 public refundSlippage;
// emitted every time when user gets crypto or tokens after success crossChainSwap
event TransferFromOtherBlockchain(
address user,
uint256 amount,
uint256 amountWithoutFee,
bytes32 originalTxHash
);
// emitted every time when user get a refund
event userRefunded(
address user,
uint256 amount,
uint256 amountWithoutFee,
bytes32 originalTxHash
);
// emitted if the recipient should receive crypto in the target blockchain
event TransferCryptoToOtherBlockchainUser(
uint256 blockchain,
address sender,
uint256 RBCAmountIn,
uint256 amountSpent,
string newAddress,
uint256 cryptoOutMin,
address[] path
);
// emitted if the recipient should receive tokens in the target blockchain
event TransferTokensToOtherBlockchainUser(
uint256 blockchain,
address sender,
uint256 RBCAmountIn,
uint256 amountSpent,
string newAddress,
uint256 tokenOutMin,
address[] path
);
/**
* @param blockchain Number of blockchain
* @param tokenInAmount Maximum amount of a token being sold
* @param firstPath Path used for swapping tokens to *RBC (tokenIn address,.., *RBC addres)
* @param secondPath Path used for swapping *RBC to tokenOut (*RBC address,.., tokenOut address)
* @param exactRBCtokenOut Exact amount of RBC to get after first swap
* @param tokenOutMin Minimal amount of tokens (or crypto) to get after second swap
* @param newAddress Address in the blockchain to which the user wants to transfer
* @param swapToCrypto This must be _true_ if swapping tokens to desired blockchain's crypto
*/
struct swapToParams {
uint256 blockchain;
uint256 tokenInAmount;
address[] firstPath;
address[] secondPath;
uint256 exactRBCtokenOut;
uint256 tokenOutMin;
string newAddress;
bool swapToCrypto;
}
/**
* @param user User address // "newAddress" from event
* @param amountWithFee Amount of tokens with included fees to transfer from the pool // "RBCAmountIn" from event
* @param amountOutMin Minimal amount of tokens to get after second swap // "tokenOutMin" from event
* @param path Path used for a second swap // "secondPath" from event
* @param originalTxHash Hash of transaction from other network, on which swap was called
* @param concatSignatures Concatenated string of signature bytes for verification of transaction
*/
struct swapFromParams {
address user;
uint256 amountWithFee;
uint256 amountOutMin;
address[] path;
bytes32 originalTxHash;
bytes concatSignatures;
}
/**
* @dev throws if transaction sender is not in owner role
*/
modifier onlyOwner() {
require(
hasRole(OWNER_ROLE, _msgSender()),
"Caller is not in owner role"
);
_;
}
/**
* @dev throws if transaction sender is not in owner or manager role
*/
modifier onlyOwnerAndManager() {
require(
hasRole(OWNER_ROLE, _msgSender()) ||
hasRole(MANAGER_ROLE, _msgSender()),
"Caller is not in owner or manager role"
);
_;
}
/**
* @dev throws if transaction sender is not in relayer role
*/
modifier onlyRelayer() {
require(
hasRole(RELAYER_ROLE, _msgSender()),
"swapContract: Caller is not in relayer role"
);
_;
}
/**
* @dev Performs check before swap*ToOtherBlockchain-functions and emits events
* @param params The swapToParams structure
* @param value The msg.value
*/
modifier TransferTo(swapToParams memory params, uint256 value) {
require(
bytes(params.newAddress).length > 0,
"swapContract: No destination address provided"
);
require(
existingOtherBlockchain[params.blockchain] &&
params.blockchain != numOfThisBlockchain,
"swapContract: Wrong choose of blockchain"
);
require(
params.firstPath.length > 0,
"swapContract: firsPath length must be greater than 1"
);
require(
params.secondPath.length > 0,
"swapContract: secondPath length must be greater than 1"
);
require(
params.firstPath[params.firstPath.length - 1] ==
RubicAddresses[numOfThisBlockchain],
"swapContract: the last address in the firstPath must be Rubic"
);
require(
params.secondPath[0] == RubicAddresses[params.blockchain],
"swapContract: the first address in the secondPath must be Rubic"
);
require(
params.exactRBCtokenOut >= minTokenAmount,
"swapContract: Not enough amount of tokens"
);
require(
params.exactRBCtokenOut < maxTokenAmount,
"swapContract: Too many RBC requested"
);
require(
value >= blockchainCryptoFee[params.blockchain],
"swapContract: Not enough crypto provided"
);
_;
if (params.swapToCrypto) {
emit TransferCryptoToOtherBlockchainUser(
params.blockchain,
_msgSender(),
params.exactRBCtokenOut,
params.tokenInAmount,
params.newAddress,
params.tokenOutMin,
params.secondPath
);
} else {
emit TransferTokensToOtherBlockchainUser(
params.blockchain,
_msgSender(),
params.exactRBCtokenOut,
params.tokenInAmount,
params.newAddress,
params.tokenOutMin,
params.secondPath
);
}
}
/**
* @dev Performs check before swap*ToUser-functions
* @param params The swapFromParams structure
*/
modifier TransferFrom(swapFromParams memory params) {
require(
params.amountWithFee >= minTokenAmount,
"swapContract: Not enough amount of tokens"
);
require(
params.amountWithFee < maxTokenAmount,
"swapContract: Too many RBC requested"
);
require(
params.path.length > 0,
"swapContract: path length must be greater than 1"
);
require(
params.path[0] == RubicAddresses[numOfThisBlockchain],
"swapContract: the first address in the path must be Rubic"
);
require(
params.user != address(0),
"swapContract: Address cannot be zero address"
);
require(
params.concatSignatures.length % SIGNATURE_LENGTH == 0,
"swapContract: Signatures lengths must be divisible by 65"
);
require(
params.concatSignatures.length / SIGNATURE_LENGTH >=
minConfirmationSignatures,
"swapContract: Not enough signatures passed"
);
_processTransaction(
params.user,
params.amountWithFee,
params.originalTxHash,
params.concatSignatures
);
_;
}
/**
* @dev Constructor of contract
* @param _numOfThisBlockchain Number of blockchain where contract is deployed
* @param _numsOfOtherBlockchains List of blockchain number that is supported by bridge
* @param tokenLimits A list where 0 element is minTokenAmount and 1 is maxTokenAmount
* @param _maxGasPrice Maximum gas price on which relayer nodes will operate
* @param _minConfirmationBlocks Minimal amount of blocks for confirmation on validator nodes
* @param _refundSlippage Slippage represented as hundredths of a bip, i.e. 1e-6 that will be used on refund
* @param _RubicAddresses Addresses of Rubic in different blockchains
*/
constructor(
uint128 _numOfThisBlockchain,
uint128[] memory _numsOfOtherBlockchains,
uint256[] memory tokenLimits,
uint256 _maxGasPrice,
uint256 _minConfirmationBlocks,
uint256 _refundSlippage,
IUniswapV2Router02 _blockchainRouter,
address[] memory _RubicAddresses
) {
for (uint256 i = 0; i < _numsOfOtherBlockchains.length; i++) {
require(
_numsOfOtherBlockchains[i] != _numOfThisBlockchain,
"swapContract: Number of this blockchain is in array of other blockchains"
);
existingOtherBlockchain[_numsOfOtherBlockchains[i]] = true;
}
for (uint256 i = 0; i < _RubicAddresses.length; i++) {
RubicAddresses[i + 1] = _RubicAddresses[i];
}
require(_maxGasPrice > 0, "swapContract: Gas price cannot be zero");
numOfThisBlockchain = _numOfThisBlockchain;
minTokenAmount = tokenLimits[0];
maxTokenAmount = tokenLimits[1];
maxGasPrice = _maxGasPrice;
refundSlippage = _refundSlippage;
minConfirmationBlocks = _minConfirmationBlocks;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(OWNER_ROLE, _msgSender());
blockchainRouter = _blockchainRouter;
IERC20(RubicAddresses[_numOfThisBlockchain]).safeApprove(
address(_blockchainRouter),
type(uint256).max
);
}
/**
* @dev Returns true if blockchain of passed id is registered to swap
* @param blockchain number of blockchain
*/
function getOtherBlockchainAvailableByNum(uint256 blockchain)
external
view
returns (bool)
{
return existingOtherBlockchain[blockchain];
}
function _processTransaction(
address user,
uint256 amountWithFee,
bytes32 originalTxHash,
bytes memory concatSignatures
) private {
bytes32 hashedParams = getHashPacked(
user,
amountWithFee,
originalTxHash
);
uint256 statusCode = processedTransactions[originalTxHash].statusCode;
bytes32 savedHash = processedTransactions[originalTxHash].hashedParams;
require(
statusCode == 0 && savedHash != hashedParams,
"swapContract: Transaction already processed"
);
uint256 signaturesCount = concatSignatures.length /
uint256(SIGNATURE_LENGTH);
address[] memory validatorAddresses = new address[](signaturesCount);
for (uint256 i = 0; i < signaturesCount; i++) {
address validatorAddress = ecOffsetRecover(
hashedParams,
concatSignatures,
i * SIGNATURE_LENGTH
);
require(
isValidator(validatorAddress),
"swapContract: Validator address not in whitelist"
);
for (uint256 j = 0; j < i; j++) {
require(
validatorAddress != validatorAddresses[j],
"swapContract: Validator address is duplicated"
);
}
validatorAddresses[i] = validatorAddress;
}
processedTransactions[originalTxHash].hashedParams = hashedParams;
processedTransactions[originalTxHash].statusCode = 1;
}
/**
* @dev Transfers tokens from sender to the contract.
* User calls this function when he wants to transfer tokens to another blockchain.
* @notice User must have approved tokenInAmount of tokenIn
*/
function swapTokensToOtherBlockchain(swapToParams memory params)
external
payable
whenNotPaused
TransferTo(params, msg.value)
{
IERC20 tokenIn = IERC20(params.firstPath[0]);
if (params.firstPath.length > 1) {
tokenIn.safeTransferFrom(
msg.sender,
address(this),
params.tokenInAmount
);
tokenIn.safeApprove(address(blockchainRouter), 0);
tokenIn.safeApprove(
address(blockchainRouter),
params.tokenInAmount
);
uint256[] memory amounts = blockchainRouter
.swapTokensForExactTokens(
params.exactRBCtokenOut,
params.tokenInAmount,
params.firstPath,
blockchainPool,
block.timestamp
);
tokenIn.safeTransfer(
_msgSender(),
params.tokenInAmount - amounts[0]
);
params.tokenInAmount = amounts[0];
} else {
tokenIn.safeTransferFrom(
msg.sender,
blockchainPool,
params.exactRBCtokenOut
);
}
}
/**
* @dev Transfers tokens from sender to the contract.
* User calls this function when he wants to transfer tokens to another blockchain.
* @notice User must have approved tokenInAmount of tokenIn
*/
function swapCryptoToOtherBlockchain(swapToParams memory params)
external
payable
whenNotPaused
TransferTo(params, msg.value)
{
uint256 cryptoWithoutFee = msg.value -
blockchainCryptoFee[params.blockchain];
uint256[] memory amounts = blockchainRouter.swapETHForExactTokens{
value: cryptoWithoutFee
}(
params.exactRBCtokenOut,
params.firstPath,
blockchainPool,
block.timestamp
);
params.tokenInAmount = amounts[0];
bool success = payable(_msgSender()).send(
cryptoWithoutFee - amounts[0]
);
require(success, "swapContract: crypto transfer back to caller failed");
}
/**
* @dev Transfers tokens to end user in current blockchain
*/
function swapTokensToUserWithFee(swapFromParams memory params)
external
onlyRelayer
whenNotPaused
TransferFrom(params)
{
uint256 amountWithoutFee = FullMath.mulDiv(
params.amountWithFee,
1e6 - feeAmountOfBlockchain[numOfThisBlockchain],
1e6
);
IERC20 RBCToken = IERC20(params.path[0]);
if (params.path.length == 1) {
RBCToken.safeTransferFrom(
blockchainPool,
params.user,
amountWithoutFee
);
RBCToken.safeTransferFrom(
blockchainPool,
address(this),
params.amountWithFee - amountWithoutFee
);
} else {
RBCToken.safeTransferFrom(
blockchainPool,
address(this),
params.amountWithFee
);
blockchainRouter.swapExactTokensForTokens(
amountWithoutFee,
params.amountOutMin,
params.path,
params.user,
block.timestamp
);
}
emit TransferFromOtherBlockchain(
params.user,
params.amountWithFee,
amountWithoutFee,
params.originalTxHash
);
}
/**
* @dev Transfers tokens to end user in current blockchain
*/
function swapCryptoToUserWithFee(swapFromParams memory params)
external
onlyRelayer
whenNotPaused
TransferFrom(params)
{
uint256 amountWithoutFee = FullMath.mulDiv(
params.amountWithFee,
1e6 - feeAmountOfBlockchain[numOfThisBlockchain],
1e6
);
IERC20 RBCToken = IERC20(params.path[0]);
RBCToken.safeTransferFrom(
blockchainPool,
address(this),
params.amountWithFee
);
blockchainRouter.swapExactTokensForETH(
amountWithoutFee,
params.amountOutMin,
params.path,
params.user,
block.timestamp
);
emit TransferFromOtherBlockchain(
params.user,
params.amountWithFee,
amountWithoutFee,
params.originalTxHash
);
}
/**
* @dev Swaps RBC from pool to initially spent by user tokens and transfers him
* @notice There is used the same structure as in other similar functions but amountOutMin should be
* equal to the amount of tokens initially spent by user (we are refunding them), AmountWithFee should
* be equal to the amount of RBC tokens that the pool got after the first swap (RBCAmountIn in the event)
* hashedParams of this originalTxHash
*/
function refundTokensToUser(swapFromParams memory params)
external
onlyRelayer
whenNotPaused
TransferFrom(params)
{
IERC20 RBCToken = IERC20(params.path[0]);
if (params.path.length == 1) {
RBCToken.safeTransferFrom(
blockchainPool,
params.user,
params.amountOutMin
);
emit userRefunded(
params.user,
params.amountOutMin,
params.amountOutMin,
params.originalTxHash
);
} else {
uint256 amountIn = FullMath.mulDiv(
params.amountWithFee,
1e6 + refundSlippage,
1e6
);
RBCToken.safeTransferFrom(blockchainPool, address(this), amountIn);
uint256 RBCSpent = blockchainRouter.swapTokensForExactTokens(
params.amountOutMin,
amountIn,
params.path,
params.user,
block.timestamp
)[0];
RBCToken.safeTransfer(blockchainPool, amountIn - RBCSpent);
emit userRefunded(
params.user,
RBCSpent,
RBCSpent,
params.originalTxHash
);
}
}
function refundCryptoToUser(swapFromParams memory params)
external
onlyRelayer
whenNotPaused
TransferFrom(params)
{
IERC20 RBCToken = IERC20(params.path[0]);
uint256 amountIn = FullMath.mulDiv(
params.amountWithFee,
1e6 + refundSlippage,
1e6
);
RBCToken.safeTransferFrom(blockchainPool, address(this), amountIn);
uint256 RBCSpent = blockchainRouter.swapTokensForExactETH(
params.amountOutMin,
amountIn,
params.path,
params.user,
block.timestamp
)[0];
RBCToken.safeTransfer(blockchainPool, amountIn - RBCSpent);
emit userRefunded(
params.user,
RBCSpent,
RBCSpent,
params.originalTxHash
);
}
// OTHER BLOCKCHAIN MANAGEMENT
/**
* @dev Registers another blockchain for availability to swap
* @param numOfOtherBlockchain number of blockchain
*/
function addOtherBlockchain(uint128 numOfOtherBlockchain)
external
onlyOwner
{
require(
numOfOtherBlockchain != numOfThisBlockchain,
"swapContract: Cannot add this blockchain to array of other blockchains"
);
require(
!existingOtherBlockchain[numOfOtherBlockchain],
"swapContract: This blockchain is already added"
);
existingOtherBlockchain[numOfOtherBlockchain] = true;
}
/**
* @dev Unregisters another blockchain for availability to swap
* @param numOfOtherBlockchain number of blockchain
*/
function removeOtherBlockchain(uint128 numOfOtherBlockchain)
external
onlyOwner
{
require(
existingOtherBlockchain[numOfOtherBlockchain],
"swapContract: This blockchain was not added"
);
existingOtherBlockchain[numOfOtherBlockchain] = false;
}
/**
* @dev Change existing blockchain id
* @param oldNumOfOtherBlockchain number of existing blockchain
* @param newNumOfOtherBlockchain number of new blockchain
*/
function changeOtherBlockchain(
uint128 oldNumOfOtherBlockchain,
uint128 newNumOfOtherBlockchain
) external onlyOwner {
require(
oldNumOfOtherBlockchain != newNumOfOtherBlockchain,
"swapContract: Cannot change blockchains with same number"
);
require(
newNumOfOtherBlockchain != numOfThisBlockchain,
"swapContract: Cannot add this blockchain to array of other blockchains"
);
require(
existingOtherBlockchain[oldNumOfOtherBlockchain],
"swapContract: This blockchain was not added"
);
require(
!existingOtherBlockchain[newNumOfOtherBlockchain],
"swapContract: This blockchain is already added"
);
existingOtherBlockchain[oldNumOfOtherBlockchain] = false;
existingOtherBlockchain[newNumOfOtherBlockchain] = true;
}
/**
* @dev Changes/Set Router address
* @param _router the new Router address
*/
function setRouter(IUniswapV2Router02 _router)
external
onlyOwnerAndManager
{
blockchainRouter = _router;
}
/**
* @dev Changes/Set Pool address
* @param _poolAddress the new Pool address
*/
function setPoolAddress(address _poolAddress) external onlyOwnerAndManager {
blockchainPool = _poolAddress;
}
// FEE MANAGEMENT
/**
* @dev Sends collected crypto fee to the owner
*/
function collectCryptoFee() external onlyOwner {
bool success = payable(msg.sender).send(address(this).balance);
require(success, "swapContract: fail collecting fee");
}
/**
* @dev Sends collected token fee to the owner
*/
function collectTokenFee() external onlyOwner {
IERC20(RubicAddresses[numOfThisBlockchain]).safeTransfer(
msg.sender,
IERC20(RubicAddresses[numOfThisBlockchain]).balanceOf(address(this))
);
}
/**
* @dev Changes fee values for blockchains in feeAmountOfBlockchain variables
* @notice fee is represented as hundredths of a bip, i.e. 1e-6
* @param _blockchainNum Existing number of blockchain
* @param feeAmount Fee amount to substruct from transfer amount
*/
function setFeeAmountOfBlockchain(uint128 _blockchainNum, uint256 feeAmount)
external
onlyOwnerAndManager
{
feeAmountOfBlockchain[_blockchainNum] = feeAmount;
}
/**
* @dev Changes crypto fee values for blockchains in blockchainCryptoFee variables
* @param _blockchainNum Existing number of blockchain
* @param feeAmount Fee amount that must be sent calling transferToOtherBlockchain
*/
function setCryptoFeeOfBlockchain(uint128 _blockchainNum, uint256 feeAmount)
external
onlyOwnerAndManager
{
blockchainCryptoFee[_blockchainNum] = feeAmount;
}
/**
* @dev Changes the address of Rubic in the certain blockchain
* @param _blockchainNum Existing number of blockchain
* @param _RubicAddress The Rubic address
*/
function setRubicAddressOfBlockchain(
uint128 _blockchainNum,
address _RubicAddress
) external onlyOwnerAndManager {
RubicAddresses[_blockchainNum] = _RubicAddress;
if (_blockchainNum == numOfThisBlockchain) {
if (
IERC20(_RubicAddress).allowance(
address(this),
address(blockchainRouter)
) != 0
) {
IERC20(_RubicAddress).safeApprove(address(blockchainRouter), 0);
}
IERC20(_RubicAddress).safeApprove(
address(blockchainRouter),
type(uint256).max
);
}
}
// VALIDATOR CONFIRMATIONS MANAGEMENT
/**
* @dev Changes requirement for minimal amount of signatures to validate on transfer
* @param _minConfirmationSignatures Number of signatures to verify
*/
function setMinConfirmationSignatures(uint256 _minConfirmationSignatures)
external
onlyOwner
{
require(
_minConfirmationSignatures > 0,
"swapContract: At least 1 confirmation can be set"
);
minConfirmationSignatures = _minConfirmationSignatures;
}
/**
* @dev Changes requirement for minimal token amount on transfers
* @param _minTokenAmount Amount of tokens
*/
function setMinTokenAmount(uint256 _minTokenAmount)
external
onlyOwnerAndManager
{
minTokenAmount = _minTokenAmount;
}
/**
* @dev Changes requirement for maximum token amount on transfers
* @param _maxTokenAmount Amount of tokens
*/
function setMaxTokenAmount(uint256 _maxTokenAmount)
external
onlyOwnerAndManager
{
maxTokenAmount = _maxTokenAmount;
}
/**
* @dev Changes parameter of maximum gas price on which relayer nodes will operate
* @param _maxGasPrice Price of gas in wei
*/
function setMaxGasPrice(uint256 _maxGasPrice) external onlyOwnerAndManager {
require(_maxGasPrice > 0, "swapContract: Gas price cannot be zero");
maxGasPrice = _maxGasPrice;
}
/**
* @dev Changes requirement for minimal amount of block to consider tx confirmed on validator
* @param _minConfirmationBlocks Amount of blocks
*/
function setMinConfirmationBlocks(uint256 _minConfirmationBlocks)
external
onlyOwnerAndManager
{
minConfirmationBlocks = _minConfirmationBlocks;
}
function setRefundSlippage(uint256 _refundSlippage)
external
onlyOwnerAndManager
{
refundSlippage = _refundSlippage;
}
/**
* @dev Transfers permissions of contract ownership.
* Will setup new owner and one manager on contract.
* Main purpose of this function is to transfer ownership from deployer account ot real owner
* @param newOwner Address of new owner
* @param newManager Address of new manager
*/
function transferOwnerAndSetManager(address newOwner, address newManager)
external
onlyOwner
{
require(
newOwner != _msgSender(),
"swapContract: New owner must be different than current"
);
require(
newOwner != address(0x0),
"swapContract: Owner cannot be zero address"
);
require(
newManager != address(0x0),
"swapContract: Owner cannot be zero address"
);
_setupRole(DEFAULT_ADMIN_ROLE, newOwner);
_setupRole(OWNER_ROLE, newOwner);
_setupRole(MANAGER_ROLE, newManager);
renounceRole(OWNER_ROLE, _msgSender());
renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* @dev Pauses transfers of tokens on contract
*/
function pauseExecution() external onlyOwner {
_pause();
}
/**
* @dev Resumes transfers of tokens on contract
*/
function continueExecution() external onlyOwner {
_unpause();
}
/**
* @dev Function to check if address is belongs to owner role
* @param account Address to check
*/
function isOwner(address account) public view returns (bool) {
return hasRole(OWNER_ROLE, account);
}
/**
* @dev Function to check if address is belongs to manager role
* @param account Address to check
*/
function isManager(address account) public view returns (bool) {
return hasRole(MANAGER_ROLE, account);
}
/**
* @dev Function to check if address is belongs to relayer role
* @param account Address to check
*/
function isRelayer(address account) public view returns (bool) {
return hasRole(RELAYER_ROLE, account);
}
/**
* @dev Function to check if address is belongs to validator role
* @param account Address to check
*
*/
function isValidator(address account) public view returns (bool) {
return hasRole(VALIDATOR_ROLE, account);
}
/**
* @dev Function changes values associated with certain originalTxHash
* @param originalTxHash Transaction hash to change
* @param statusCode Associated status: 0-Not processed, 1-Processed, 2-Reverted
* @param hashedParams Hashed params with which the initial transaction was executed
*/
function changeTxStatus(
bytes32 originalTxHash,
uint256 statusCode,
bytes32 hashedParams
) external onlyRelayer {
require(
statusCode != 0,
"swapContract: you cannot set the statusCode to 0"
);
require(
processedTransactions[originalTxHash].statusCode != 1,
"swapContract: transaction with this originalTxHash has already been set as succeed"
);
processedTransactions[originalTxHash].statusCode = statusCode;
processedTransactions[originalTxHash].hashedParams = hashedParams;
}
/**
* @dev Plain fallback function to receive crypto
*/
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract ECDSAOffsetRecovery {
function getHashPacked(
address user,
uint256 amountWithFee,
bytes32 originalTxHash
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(user, amountWithFee, originalTxHash));
}
function toEthSignedMessageHash(bytes32 hash)
public
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)
);
}
function ecOffsetRecover(
bytes32 hash,
bytes memory signature,
uint256 offset
) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Divide the signature in r, s and v variables with inline assembly.
assembly {
r := mload(add(signature, add(offset, 0x20)))
s := mload(add(signature, add(offset, 0x40)))
v := byte(0, mload(add(signature, add(offset, 0x60))))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
}
// bytes memory prefix = "\x19Ethereum Signed Message:\n32";
// hash = keccak256(abi.encodePacked(prefix, hash));
// solium-disable-next-line arg-overflow
return ecrecover(toEthSignedMessageHash(hash), v, r, s);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @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);
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
|
Transfers tokens from sender to the contract. User calls this function when he wants to transfer tokens to another blockchain. User must have approved tokenInAmount of tokenIn/
|
function swapTokensToOtherBlockchain(swapToParams memory params)
external
payable
whenNotPaused
TransferTo(params, msg.value)
{
IERC20 tokenIn = IERC20(params.firstPath[0]);
if (params.firstPath.length > 1) {
tokenIn.safeTransferFrom(
msg.sender,
address(this),
params.tokenInAmount
);
tokenIn.safeApprove(address(blockchainRouter), 0);
tokenIn.safeApprove(
address(blockchainRouter),
params.tokenInAmount
);
uint256[] memory amounts = blockchainRouter
.swapTokensForExactTokens(
params.exactRBCtokenOut,
params.tokenInAmount,
params.firstPath,
blockchainPool,
block.timestamp
);
tokenIn.safeTransfer(
_msgSender(),
params.tokenInAmount - amounts[0]
);
params.tokenInAmount = amounts[0];
tokenIn.safeTransferFrom(
msg.sender,
blockchainPool,
params.exactRBCtokenOut
);
}
}
| 624,875 |
./full_match/1/0x692EFFB3F67c6e04aB2D91bd714fdc985D391377/sources/browser/arb.sol
|
require(all_routers.length == all_factories.length, "error0");address factory = all_routers[all_routers.length /2 + i];uint[] memory outs = ;
|
function getMaxAmountAndRouter(address[] memory all_routers,
address[] memory path, uint amount,address pending_pair, uint[2] memory pending_amount, address tokenIn ) public view returns(uint amoutOut, address router){
for (uint i = 0; i< all_routers.length /2 ; i++){
uint r1 = 0;
uint r2 = 0;
address t0;
address pair= IUniswapV2Factory(all_routers[all_routers.length /2 + i]).getPair(path[0],path[1]);
if (pair!=address(0)){
(r1, r2 ,) = IUniswapV2Pair(pair).getReserves();
t0 = IUniswapV2Pair(pair).token0();
}
if (r1>0 && r2 >0){
uint curAmountOut;
if (pending_pair== pair){
(r1,r2) = updateNewReserve(all_routers[i],pending_amount[0],pending_amount[1],r1,r2,tokenIn, t0);
if (path[0] == t0){
curAmountOut = IUniswapV2Router01(all_routers[i]).getAmountOut(amount, r1 ,r2);
curAmountOut = IUniswapV2Router01(all_routers[i]).getAmountOut(amount, r2 ,r1);
}
}
else{
curAmountOut = IUniswapV2Router01(all_routers[i]).getAmountsOut(amount, path)[1];
}
if (amoutOut < curAmountOut){
amoutOut = curAmountOut;
router = all_routers[i];
}
}
}
return (amoutOut, router);
}
| 8,354,715 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.10;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./oracleClient/IOracleClient.sol";
import "./NFTwe.sol";
import "./utils/WadMath.sol";
import "./utils/TweetContent.sol";
/**
* @dev Tweether Protocol gov contract
* @author Alex Roan (@alexroan)
*/
contract Tweether is ERC20{
using WadMath for uint;
using TweetContent for string;
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev LINK token address
*/
IERC20 public link;
/**
* @dev Oracle contract to tweet from
*/
IOracleClient public oracleclient;
/**
* @dev NFTwe
*/
NFTwe public nftwe;
/**
* @dev WAD format Tweether denominator which determines ratios for proposals and votes.
*/
uint public tweetherDenominator;
struct Tweet {
address proposer;
uint expiry;
string content;
uint votes;
bool accepted;
EnumerableSet.AddressSet voters;
}
Tweet[] private proposals;
// Votes per proposal per address
mapping(address => mapping(uint => uint)) public voteAmounts;
mapping(address => uint) public lockedVotes;
event TweetProposed(uint proposalId, address proposer, uint expiryDate);
event VoteCast(uint proposalId, address voter, uint amount);
event VoteUncast(uint proposalId, address voter, uint amount);
event TweetAccepted(uint proposalId, address finalVoter);
/**
* Construct using a pre-constructed IOracleClient
* @param oracleclientAddress address referencing pre-deployed IOracleClient
* @param nftweAddress address of the NFTwe contractto mint to voters
* @param denominator WAD format representing the Tweether Denominator,
* used in a range of protocol calculations
*/
constructor(address oracleclientAddress, address nftweAddress, uint denominator) public ERC20("Tweether", "TWE") {
oracleclient = IOracleClient(oracleclientAddress);
link = IERC20(oracleclient.paymentTokenAddress());
nftwe = NFTwe(nftweAddress);
tweetherDenominator = denominator;
}
/**
* @dev Require that a holder can't send their TWE until they
* have unlocked their TWE votes from proposals.
* @param from address
*/
function _beforeTokenTransfer(address from, address, uint256) internal override {
require(lockedVotes[from] == 0, "Unlock TWE votes before transfer");
}
/**
* @dev Mint TWE by supplying LINK. LINK.approve must first be called by msg.sender
* @param linkAmount the amount of LINK to supply
* @return amount of TWE minted
*/
function mint(uint linkAmount) external returns (uint) {
// First mint enters here and returns
if (totalSupply() == 0 || linkBalance() == 0) {
return _mint(linkAmount, linkAmount);
}
// For any other mint...
uint tweMinted = (linkAmount.wadMul(totalSupply())).wadDiv(linkBalance());
return _mint(linkAmount, tweMinted);
}
/**
* @dev Internal mint function
* @param linkAmount the amount of LINK to request from the sender
* @param tweToMint the amount of TWE to mint
* @return amount of TWE minted
*/
function _mint(uint linkAmount, uint tweToMint) internal returns (uint) {
require(link.transferFrom(msg.sender, address(this), linkAmount), "LINK not supplied");
_mint(msg.sender, tweToMint);
return tweToMint;
}
/**
* @dev Burn TWE, receiving LINK.
* @param tweAmount amount of TWE to burn
* @return LINK returned
*/
function burn(uint tweAmount) external returns (uint) {
require(linkBalance() >= WadMath.WAD, "Not enough LINK");
require(totalSupply() >= WadMath.WAD, "Not enough totalSupply");
uint linkReturned = tweAmount.wadMul(tweValueInLink());
_burn(msg.sender, tweAmount);
require(link.transfer(msg.sender, linkReturned), "LINK transfer fail");
return linkReturned;
}
/**
* @dev Unvote from a proposal
* @param proposalId ID of tweet proposal
* @param numberOfVotes number of votes to unvote
*/
function unvote(uint proposalId, uint numberOfVotes) external {
// Does the tweet exist?
require(proposalId < proposals.length, "Proposal doesn't exist");
// Has the proposal been accepted already?
require(proposals[proposalId].accepted != true, "Proposal accepted already");
// decrease number of votes of the tweet
uint totalVotes = proposals[proposalId].votes.sub(numberOfVotes);
proposals[proposalId].votes = totalVotes;
// decrease vote amounts for user on proposal
voteAmounts[msg.sender][proposalId] = voteAmounts[msg.sender][proposalId].sub(numberOfVotes);
lockedVotes[msg.sender] = lockedVotes[msg.sender].sub(numberOfVotes);
// if the remaining votes on this proposal, by this address is now 0
// remove them from the list of voters
if (totalVotes == 0) {
// remove from list of voters
proposals[proposalId].voters.remove(msg.sender);
}
emit VoteUncast(proposalId, msg.sender, numberOfVotes);
checkVoteCount(proposalId);
}
/**
* @dev Vote on a proposal
* @param proposalId ID of proposal
* @param numberOfVotes votes to cast on proposal
*/
function vote(uint proposalId, uint numberOfVotes) external {
// Does the tweet exist?
require(proposalId < proposals.length, "Proposal doesn't exist");
// Has the proposal been accepted already?
require(proposals[proposalId].accepted != true, "Proposal accepted already");
// Is the proposal valid?
require(proposals[proposalId].expiry > block.timestamp, "Proposal expired");
// Does the sender have enough TWE for votes
// Does the sender have enough TWE not locked in votes already?
require(balanceOf(msg.sender).sub(lockedVotes[msg.sender]) >= numberOfVotes, "Not enough unlocked TWE");
// Add to list of voters
proposals[proposalId].voters.add(msg.sender);
// Add to voteAmounts
voteAmounts[msg.sender][proposalId] = voteAmounts[msg.sender][proposalId].add(numberOfVotes);
lockedVotes[msg.sender] = lockedVotes[msg.sender].add(numberOfVotes);
// Vote on tweet
uint totalVotes = proposals[proposalId].votes.add(numberOfVotes);
proposals[proposalId].votes = totalVotes;
emit VoteCast(proposalId, msg.sender, numberOfVotes);
checkVoteCount(proposalId);
}
/**
* @dev Check the vote count of a proposal and tweet if
* it exceeds the votesRequired
* @param proposalId Tweet proposal ID
*/
function checkVoteCount(uint proposalId) public {
uint totalVotes = proposals[proposalId].votes;
// If votes tip over edge, accept tweet
if (totalVotes >= votesRequired()) {
_acceptTweet(proposalId);
}
}
function _acceptTweet(uint proposalId) internal {
proposals[proposalId].accepted = true;
// Unlock votes, but maintain history in proposal
for (uint index = 0; index < proposals[proposalId].voters.length(); index++) {
address voter = proposals[proposalId].voters.at(index);
lockedVotes[voter] = lockedVotes[voter].sub(voteAmounts[voter][proposalId]);
voteAmounts[voter][proposalId] = 0;
}
emit TweetAccepted(proposalId, msg.sender);
(uint price,) = oracleCost();
link.approve(address(oracleclient), price);
oracleclient.sendTweet(proposals[proposalId].content);
nftwe.newTweet(
proposals[proposalId].proposer,
proposals[proposalId].content,
block.timestamp,
msg.sender
);
}
/**
* @dev Votes required to tweet a proposal
* @return Number of TWE votes required
*/
function votesRequired() public view returns (uint) {
// totalSupply / denominator
return totalSupply().wadDiv(tweetherDenominator);
}
/**
* @dev Propose a tweet which can be voted on until proposal expires.
* Expiry date is set using the daysValid parameter.
* @param daysValid number of days for this proposal to be valid before expiry
* @param tweetContent the text content of the tweet
* @return Tweet proposal ID
*/
function proposeTweet(uint daysValid, string memory tweetContent) external returns (uint) {
require(tweetContent.fitsInTweet(), "Invalid tweet size");
uint daysValidPrice = daysValid.mul(tweSingleProposalCost());
uint expiryDate = block.timestamp + daysValid.mul(24).mul(60).mul(60);
_burn(msg.sender, daysValidPrice);
uint256 newId = proposals.length;
EnumerableSet.AddressSet memory newVoters;
proposals.push(
Tweet(
msg.sender,
expiryDate,
tweetContent,
0,
false,
newVoters
)
);
emit TweetProposed(newId, msg.sender, expiryDate);
return newId;
}
/**
* @dev get a proposal
* @param id proposal ID
* @return proposer address
* @return expiry date
* @return content string
* @return votes for
* @return boolean has been accepted
*/
function getTweetProposal(uint id) external view returns (address, uint, string memory, uint, bool) {
Tweet memory prop = proposals[id];
return (
prop.proposer,
prop.expiry,
prop.content,
prop.votes,
prop.accepted
);
}
/**
* @dev The TWE cost of submitting a proposal for 1 day timespan
* @return TWE cost
*/
function tweSingleProposalCost() public view returns (uint) {
// (oracleCost * totalTweSupply) / (denominator * linkBalance)
(uint oracleCost, ) = oracleCost();
return (oracleCost.wadMul(totalSupply())).wadDiv(tweetherDenominator.wadMul(linkBalance()));
}
/**
* @dev Get the cost of a request to the oracle
* @return (uint price, uint decimals)
*/
function oracleCost() public view returns (uint, uint) {
return oracleclient.getPrice();
}
/**
* @dev Get the current balance of LINK
* @return balance
*/
function linkBalance() public view returns (uint) {
return link.balanceOf(address(this));
}
/**
* @dev Get the current value of TWE in LINK
* @return TWE value
*/
function tweValueInLink() public view returns (uint) {
return linkBalance().wadDiv(totalSupply());
}
}
|
Get the current balance of LINK return balance/
|
function linkBalance() public view returns (uint) {
return link.balanceOf(address(this));
}
| 2,475,899 |
./full_match/97/0x091Fbe77E46FC560D6cD7cf3bC01aE990847dDbA/sources/project_/contracts/BetDex.sol
|
if (myBet.resolved) { continue; } myBet.resolved = true;
|
function resolveBet(
uint256 matchId,
uint16 gameType,
uint16[] calldata _targets
) external nonReentrant onlyRole(ROLE_MANAGER) {
uint256 length = gameBets[matchId][gameType].length();
uint256 targetLength = _targets.length;
require(length > 0, "NO_BETS");
for (uint i = 0; i < targetLength; unchecked_inc(i)) {
targets[_targets[i]] = true;
}
for (uint i = 0; i < length; unchecked_inc(i)) {
bytes32 betSlipId = gameBets[matchId][gameType].at(i);
Bet memory myBet = bets[betSlipId];
gameBets[matchId][gameType].remove(betSlipId);
bool valid = targets[myBet.target];
bool result = valid;
uint256 potentialWinningAmount = myBet.potentialWinningAmount;
if (valid) {
lockUserBalance(
myBet.roomId,
myBet.bettor
);
userBalances[myBet.roomId][
myBet.bettor
] += potentialWinningAmount;
unlockUserBalance(
myBet.roomId,
myBet.bettor
);
lockRoomReverse(myBet.roomId);
rooms[myBet.roomId].reverse -= potentialWinningAmount;
rooms[myBet.roomId].lockedReverse -= potentialWinningAmount;
unlockRoomReverse(myBet.roomId);
lockRoomReverse(myBet.roomId);
rooms[myBet.roomId].lockedReverse -= potentialWinningAmount;
unlockRoomReverse(myBet.roomId);
potentialWinningAmount = 0;
}
emit BetResolved(
myBet.roomId,
myBet.bettor,
betSlipId,
myBet.target,
result,
);
delete bets[betSlipId];
}
for (uint i = 0; i < targetLength; unchecked_inc(i)) {
targets[_targets[i]] = false;
}
}
| 5,044,254 |
./full_match/43113/0xf00bFd6D592de8E77fCB597A7b9eDe34DB98AE68/sources/github/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(
blockNumber < block.number,
"EGG::getPriorVotes: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 13,198,253 |
pragma solidity ^0.4.4;
import "Marketplace.sol";
contract StandardMarketplace is Marketplace {
/* Fields */
address private owner;
Token public token;
/* Mappings */
mapping(address => Offer) public offers; //Tradeable => Offer
mapping(address => mapping(address => uint)) private balance; //Tradeable => Buyer => Balance
/* Modifiers */
modifier isBuyerOf(Tradeable _item) { if(offers[_item].buyer == msg.sender) _; else throw; }
modifier isOwnerOf(Tradeable _item) { if(msg.sender == _item.owner()) _; else throw; }
modifier isAuthorizedToSell(Tradeable _item) { if(_item.isAuthorizedToSell(this)) _; else throw; }
function StandardMarketplace(Token _token) {
token = _token;
if(token.totalSupply() <= 0) throw; //This seams to be an invalid contract
if(token.balanceOf(this) != 0) throw;
}
function extendOffer(Tradeable _item, address _buyer, uint _price)
isOwnerOf(_item)
isAuthorizedToSell(_item)
returns (bool success) {
if(offers[_item].state != OfferStates.Initial) return false;
if(_price < 0) return false;
addOffer(_item, Offer({
seller: msg.sender,
buyer: _buyer,
amount:_price,
state: OfferStates.Extended
}));
SellerAddedOffer(_item);
return true;
}
function acceptOffer(Tradeable _item) isBuyerOf(_item) returns (bool success) {
var offer = offers[_item];
/* Offer can only be accepted once */
if(offer.state != OfferStates.Extended) return false;
if(offer.amount > 0){
/* Check if the buyer have sufficient funds */
if(token.allowance(offer.buyer, this) < offer.amount) return false;
/* Transfer funds from the buyer to the market */
if(!token.transferFrom(offer.buyer, this, offer.amount)) throw;
balance[_item][offer.buyer] = offer.amount;
}
/* Accept the offer */
offer.state = OfferStates.Accepted;
BuyerAcceptedOffer(_item);
return true;
}
function revokeOffer(Tradeable _item) isOwnerOf(_item) returns (bool success) {
var offer = offers[_item];
/* If the offer is not added then the state is initial */
if(offers[_item].state == OfferStates.Initial) return false;
var amount = balance[_item][offer.buyer];
if(offer.state == OfferStates.Accepted && amount > 0) {
/* transferring all locked funds back to the buyer */
balance[_item][offer.buyer] = 0;
if(!token.transfer(offer.buyer, amount)) throw;
}
/* Revoke offer */
SellerRevokedOffer(_item);
removeOffer(_item, offers[_item]);
return true;
}
function completeTransaction(Tradeable _item) isBuyerOf(_item)
returns (bool success) {
/* Getting the offer */
var offer = offers[_item];
/* Can only complete the transaction if the offer was accepted */
if(offer.state != OfferStates.Accepted) return false;
if(offer.amount > 0){
/* The buyer must have sufficient funds */
if(balance[_item][offer.buyer] < offer.amount) return false;
/* Transferring funds to the seller */
balance[_item][offer.buyer] -= offer.amount;
if(!token.transfer(offer.seller, offer.amount)) throw;
}
/* Transferring ownership to the buyer */
_item.transferOwnership(offer.buyer);
BuyerCompletedTransaction(_item);
removeOffer(_item, offers[_item]);
return true;
}
function abortTransaction(Tradeable _item) isBuyerOf(_item)
returns (bool success) {
/* Getting the offer */
var offer = offers[_item];
/* Can only abort the transaction if the offer was accepted */
if(offer.state != OfferStates.Accepted) return false;
/* Transferring all locked funds back to the buyer */
var amount = balance[_item][offer.buyer];
if(amount > 0){
balance[_item][offer.buyer] = 0;
if(!token.transfer(offer.buyer, amount)) throw;
}
/* Cancel sale of the item */
BuyerAbortedTransaction(_item);
removeOffer(_item, offers[_item]);
return true;
}
function addOffer(Tradeable _item, Offer _offer) private {
offers[_item] = _offer;
onOfferAdded(_item,_offer);
}
function removeOffer(Tradeable _item, Offer _offer) private {
delete offers[_item];
onOfferRemoved(_item,_offer);
}
function onOfferAdded(Tradeable _item, Offer _offer) internal {}
function onOfferRemoved(Tradeable _item, Offer _offer) internal {}
enum OfferStates { Initial, Extended, Accepted }
struct Offer {
address seller;
address buyer;
uint amount; //The purchase cost
OfferStates state; //Whether or not the offer is accepted
}
/* Ether can't be transferred to this account */
function () { throw; }
}
|
Getting the offer / Can only abort the transaction if the offer was accepted / Transferring all locked funds back to the buyer /
|
function abortTransaction(Tradeable _item) isBuyerOf(_item)
returns (bool success) {
var offer = offers[_item];
if(offer.state != OfferStates.Accepted) return false;
var amount = balance[_item][offer.buyer];
if(amount > 0){
balance[_item][offer.buyer] = 0;
if(!token.transfer(offer.buyer, amount)) throw;
}
removeOffer(_item, offers[_item]);
return true;
}
| 12,965,210 |
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2021 Kentaro Hara
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
pragma solidity ^0.8.11;
import "../JohnLawCoin.sol";
//------------------------------------------------------------------------------
// [JohnLawCoin contract]
//
// JohnLawCoin is implemented as ERC20 tokens.
//
// Permission: Except public getters, only the ACB can call the methods.
// Coin holders can transfer their coins using the ERC20 token APIs.
//------------------------------------------------------------------------------
contract JohnLawCoin_v2 is ERC20PausableUpgradeable, OwnableUpgradeable {
// Constants.
// Name of the ERC20 token.
string public constant NAME = "JohnLawCoin";
// Symbol of the ERC20 token.
string public constant SYMBOL = "JLC";
// The initial coin supply.
uint public constant INITIAL_COIN_SUPPLY = 10000000;
// The tax rate.
uint public constant TAX_RATE = 1;
// Attributes.
// The account to which the tax is sent.
address public tax_account_;
address public tax_account_v2_;
mapping (address => uint) public dummy_;
// Events.
event TransferEvent(address indexed sender, address receiver,
uint amount, uint tax);
function upgrade()
public onlyOwner {
tax_account_v2_ = tax_account_;
}
// Mint coins to one account.
//
// Parameters
// ----------------
// |account|: The account to which the coins are minted.
// |amount|: The amount to be minted.
//
// Returns
// ----------------
// None.
function mint(address account, uint amount)
public onlyOwner {
mint_v2(account, amount);
}
function mint_v2(address account, uint amount)
public onlyOwner {
_mint(account, amount);
dummy_[account] = amount;
}
// Burn coins from one account.
//
// Parameters
// ----------------
// |account|: The account from which the coins are burned.
// |amount|: The amount to be burned.
//
// Returns
// ----------------
// None.
function burn(address account, uint amount)
public onlyOwner {
burn_v2(account, amount);
}
function burn_v2(address account, uint amount)
public onlyOwner {
_burn(account, amount);
dummy_[account] = amount;
}
// Move coins from one account to another account. Coin holders should use
// ERC20's transfer method instead.
//
// Parameters
// ----------------
// |sender|: The sender account.
// |receiver|: The receiver account.
// |amount|: The amount to be moved.
//
// Returns
// ----------------
// None.
function move(address sender, address receiver, uint amount)
public onlyOwner {
move_v2(sender, receiver, amount);
}
function move_v2(address sender, address receiver, uint amount)
public onlyOwner {
_transfer(sender, receiver, amount);
dummy_[receiver] = amount;
}
// Pause the contract.
function pause()
public onlyOwner {
if (!paused()) {
_pause();
}
}
// Unpause the contract.
function unpause()
public onlyOwner {
if (paused()) {
_unpause();
}
}
// Override decimals.
function decimals()
public pure override returns (uint8) {
return 18;
}
// Set the tax rate.
function resetTaxAccount()
public onlyOwner {
resetTaxAccount_v2();
}
function resetTaxAccount_v2()
public onlyOwner {
address old_tax_account = tax_account_v2_;
tax_account_v2_ = address(uint160(uint(keccak256(abi.encode(
"tax_v2", block.number)))));
move(old_tax_account, tax_account_v2_, balanceOf(old_tax_account));
tax_account_v2_ = tax_account_;
}
// Override ERC20's transfer method to impose a tax set by the ACB.
//
// Parameters
// ----------------
// |account|: The receiver account.
// |amount|: The amount to be transferred.
//
// Returns
// ----------------
// None.
function transfer(address account, uint amount)
public override returns (bool) {
return transfer_v2(account, amount);
}
function transfer_v2(address account, uint amount)
public returns (bool) {
uint tax = amount * TAX_RATE / 100;
_transfer(_msgSender(), tax_account_v2_, tax);
_transfer(_msgSender(), account, amount - tax);
emit TransferEvent(_msgSender(), account, amount - tax, tax);
return true;
}
}
//------------------------------------------------------------------------------
// [JohnLawBond contract]
//
// JohnLawBond is an implementation of the bonds to increase / decrease the
// total coin supply. The bonds are not transferable.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract JohnLawBond_v2 is OwnableUpgradeable {
using EnumerableSet for EnumerableSet.UintSet;
// Attributes.
// _bonds[account][redemption_epoch] stores the number of the bonds
// owned by the |account| that become redeemable at |redemption_epoch|.
mapping (address => mapping (uint => uint)) private _bonds;
// _redemption_epochs[account] is a set of the redemption epochs of the
// bonds owned by the |account|.
mapping (address => EnumerableSet.UintSet) private _redemption_epochs;
// _bond_count[account] is the number of the bonds owned by the |account|.
mapping (address => uint) private _bond_count;
// _bond_supply[redemption_epoch] is the total number of the bonds that
// become redeemable at |redemption_epoch|.
mapping (uint => uint) private _bond_supply;
// The total bond supply.
uint private _total_supply;
uint private _total_supply_v2;
mapping (address => mapping (uint => uint)) private _bonds_v2;
mapping (address => EnumerableSet.UintSet) private _redemption_epochs_v2;
mapping (address => uint) private _bond_count_v2;
mapping (uint => uint) private _bond_supply_v2;
// Events.
event MintEvent(address indexed account, uint redemption_epoch, uint amount);
event BurnEvent(address indexed account, uint redemption_epoch, uint amount);
function upgrade()
public onlyOwner {
_total_supply_v2 = _total_supply;
for (uint epoch = 0; epoch < 100; epoch++) {
_bond_supply_v2[epoch] = _bond_supply[epoch];
}
}
// Mint bonds to one account.
//
// Parameters
// ----------------
// |account|: The account to which the bonds are minted.
// |redemption_epoch|: The redemption epoch of the bonds.
// |amount|: The amount to be minted.
//
// Returns
// ----------------
// None.
function mint(address account, uint redemption_epoch, uint amount)
public onlyOwner {
mint_v2(account, redemption_epoch, amount);
}
function mint_v2(address account, uint redemption_epoch, uint amount)
public onlyOwner {
_bonds[account][redemption_epoch] += amount;
_bonds_v2[account][redemption_epoch] += amount;
_total_supply_v2 += amount;
_bond_count[account] += amount;
_bond_count_v2[account] += amount;
_bond_supply[redemption_epoch] += amount;
_bond_supply_v2[redemption_epoch] += amount;
if (_bonds[account][redemption_epoch] > 0) {
_redemption_epochs[account].add(redemption_epoch);
_redemption_epochs_v2[account].add(redemption_epoch);
}
emit MintEvent(account, redemption_epoch, amount);
}
// Burn bonds from one account.
//
// Parameters
// ----------------
// |account|: The account from which the bonds are burned.
// |redemption_epoch|: The redemption epoch of the bonds.
// |amount|: The amount to be burned.
//
// Returns
// ----------------
// None.
function burn(address account, uint redemption_epoch, uint amount)
public onlyOwner {
burn_v2(account, redemption_epoch, amount);
}
function burn_v2(address account, uint redemption_epoch, uint amount)
public onlyOwner {
_bonds[account][redemption_epoch] -= amount;
_bonds_v2[account][redemption_epoch] += amount;
_total_supply_v2 -= amount;
_bond_count[account] -= amount;
_bond_count_v2[account] += amount; // Use + to avoid underflow.
_bond_supply[redemption_epoch] -= amount;
_bond_supply_v2[redemption_epoch] -= amount;
if (_bonds[account][redemption_epoch] == 0) {
_redemption_epochs[account].remove(redemption_epoch);
_redemption_epochs_v2[account].remove(redemption_epoch);
}
emit BurnEvent(account, redemption_epoch, amount);
}
// Public getter: Return the number of the bonds owned by the |account|.
function numberOfBondsOwnedBy(address account)
public view returns (uint) {
return _bond_count[account];
}
// Public getter: Return the number of redemption epochs of the bonds
// owned by the |account|.
function numberOfRedemptionEpochsOwnedBy(address account)
public view returns (uint) {
return _redemption_epochs[account].length();
}
// Public getter: Return the |index|-th redemption epoch of the bonds
// owned by the |account|. |index| must be smaller than the value returned by
// numberOfRedemptionEpochsOwnedBy(account).
function getRedemptionEpochOwnedBy(address account, uint index)
public view returns (uint) {
return _redemption_epochs[account].at(index);
}
// Public getter: Return the number of the bonds owned by the |account| that
// become redeemable at |redemption_epoch|.
function balanceOf(address account, uint redemption_epoch)
public view returns (uint) {
return balanceOf_v2(account, redemption_epoch);
}
function balanceOf_v2(address account, uint redemption_epoch)
public view returns (uint) {
return _bonds[account][redemption_epoch];
}
// Public getter: Return the total bond supply.
function totalSupply()
public view returns (uint) {
return _total_supply_v2;
}
// Public getter: Return the number of the bonds that become redeemable at
// |redemption_epoch|.
function bondSupplyAt(uint redemption_epoch)
public view returns (uint) {
return _bond_supply_v2[redemption_epoch];
}
}
//------------------------------------------------------------------------------
// [Oracle contract]
//
// The oracle is a decentralized mechanism to determine one "truth" level
// from 0, 1, 2, ..., LEVEL_MAX - 1. The oracle uses the commit-reveal-reclaim
// voting scheme.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract Oracle_v2 is OwnableUpgradeable {
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public LEVEL_MAX;
uint public RECLAIM_THRESHOLD;
uint public PROPORTIONAL_REWARD_RATE;
// The valid phase transition is: COMMIT => REVEAL => RECLAIM.
enum Phase {
COMMIT, REVEAL, RECLAIM
}
// Commit is a struct to manage one commit entry in the commit-reveal-reclaim
// scheme.
struct Commit {
// The committed hash (filled in the commit phase).
bytes32 hash;
// The amount of deposited coins (filled in the commit phase).
uint deposit;
// The oracle level (filled in the reveal phase).
uint oracle_level;
// The phase of this commit entry.
Phase phase;
// The epoch ID when this commit entry is created.
uint epoch_id;
bytes32 hash_v2;
uint deposit_v2;
uint oracle_level_v2;
uint epoch_id_v2;
}
// Vote is a struct to aggregate voting statistics for each oracle level.
// The data is aggregated during the reveal phase and finalized at the end
// of the reveal phase.
struct Vote {
// The total amount of the coins deposited by the voters who voted for this
// oracle level.
uint deposit;
// The number of the voters.
uint count;
// Set to true when the voters for this oracle level are eligible to
// reclaim the coins they deposited.
bool should_reclaim;
// Set to true when the voters for this oracle level are eligible to
// receive a reward.
bool should_reward;
bool should_reclaim_v2;
bool should_reward_v2;
uint deposit_v2;
uint count_v2;
}
// Epoch is a struct to keep track of the states in the commit-reveal-reclaim
// scheme. The oracle creates three Epoch objects and uses them in a
// round-robin manner. For example, when the first Epoch object is in use for
// the commit phase, the second Epoch object is in use for the reveal phase,
// and the third Epoch object is in use for the reclaim phase.
struct Epoch {
// The commit entries.
mapping (address => Commit) commits;
// The voting statistics for all the oracle levels. This uses a mapping
// (instead of an array) to make the Vote struct upgradeable.
mapping (uint => Vote) votes;
// An account to store coins deposited by the voters.
address deposit_account;
// An account to store the reward.
address reward_account;
// The total amount of the reward.
uint reward_total;
// The current phase of this Epoch.
Phase phase;
address deposit_account_v2;
address reward_account_v2;
uint reward_total_v2;
Phase phase_v2;
}
// Attributes. See the comment in initialize().
// This uses a mapping (instead of an array) to make the Epoch struct
// upgradeable.
mapping (uint => Epoch) public epochs_;
uint public epoch_id_;
uint public epoch_id_v2_;
// Events.
event CommitEvent(address indexed sender, uint indexed epoch_id,
bytes32 hash, uint deposited);
event RevealEvent(address indexed sender, uint indexed epoch_id,
uint oracle_level, uint salt);
event ReclaimEvent(address indexed sender, uint indexed epoch_id,
uint deposited, uint rewarded);
event AdvancePhaseEvent(uint indexed epoch_id, uint tax, uint burned);
function upgrade()
public onlyOwner {
epoch_id_v2_ = epoch_id_;
for (uint epoch_index = 0; epoch_index < 3; epoch_index++) {
epochs_[epoch_index].deposit_account_v2 =
epochs_[epoch_index].deposit_account;
epochs_[epoch_index].reward_account_v2 =
epochs_[epoch_index].reward_account;
epochs_[epoch_index].reward_total_v2 =
epochs_[epoch_index].reward_total;
epochs_[epoch_index].phase_v2 =
epochs_[epoch_index].phase;
for (uint level = 0; level < LEVEL_MAX; level++) {
Vote storage vote = epochs_[epoch_index].votes[level];
vote.should_reclaim_v2 = vote.should_reclaim;
vote.should_reward_v2 = vote.should_reward;
vote.deposit_v2 = vote.deposit;
vote.count_v2 = vote.count;
}
}
}
// Do commit.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |hash|: The committed hash.
// |deposit|: The amount of the deposited coins.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// True if the commit succeeded. False otherwise.
function commit(address sender, bytes32 hash, uint deposit,
JohnLawCoin_v2 coin)
public onlyOwner returns (bool) {
return commit_v2(sender, hash, deposit, coin);
}
function commit_v2(address sender, bytes32 hash, uint deposit,
JohnLawCoin_v2 coin)
public onlyOwner returns (bool) {
Epoch storage epoch = epochs_[epoch_id_v2_ % 3];
require(epoch.phase_v2 == Phase.COMMIT, "co1");
if (coin.balanceOf(sender) < deposit) {
return false;
}
// One voter can commit only once per phase.
if (epoch.commits[sender].epoch_id == epoch_id_v2_) {
return false;
}
// Create a commit entry.
epoch.commits[sender] = Commit(
hash, deposit, LEVEL_MAX, Phase.COMMIT, epoch_id_v2_,
hash, deposit, LEVEL_MAX, epoch_id_v2_);
require(epoch.commits[sender].phase == Phase.COMMIT, "co2");
// Move the deposited coins to the deposit account.
coin.move(sender, epoch.deposit_account_v2, deposit);
emit CommitEvent(sender, epoch_id_v2_, hash, deposit);
return true;
}
// Do reveal.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |oracle_level|: The oracle level revealed by the voter.
// |salt|: The salt revealed by the voter.
//
// Returns
// ----------------
// True if the reveal succeeded. False otherwise.
function reveal(address sender, uint oracle_level, uint salt)
public onlyOwner returns (bool) {
return reveal_v2(sender, oracle_level, salt);
}
function reveal_v2(address sender, uint oracle_level, uint salt)
public onlyOwner returns (bool) {
Epoch storage epoch = epochs_[(epoch_id_v2_ - 1) % 3];
require(epoch.phase_v2 == Phase.REVEAL, "rv1");
if (LEVEL_MAX <= oracle_level) {
return false;
}
if (epoch.commits[sender].epoch_id != epoch_id_v2_ - 1) {
// The corresponding commit was not found.
return false;
}
// One voter can reveal only once per phase.
if (epoch.commits[sender].phase != Phase.COMMIT) {
return false;
}
epoch.commits[sender].phase = Phase.REVEAL;
// Check if the committed hash matches the revealed level and the salt.
bytes32 reveal_hash = encrypt(
sender, oracle_level, salt);
bytes32 hash = epoch.commits[sender].hash;
if (hash != reveal_hash) {
return false;
}
// Update the commit entry with the revealed level.
epoch.commits[sender].oracle_level = oracle_level;
// Count up the vote.
epoch.votes[oracle_level].deposit_v2 += epoch.commits[sender].deposit;
epoch.votes[oracle_level].count_v2 += 1;
emit RevealEvent(sender, epoch_id_v2_, oracle_level, salt);
return true;
}
// Do reclaim.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// A tuple of two values:
// - uint: The amount of the reclaimed coins. This becomes a positive value
// when the voter is eligible to reclaim their deposited coins.
// - uint: The amount of the reward. This becomes a positive value when the
// voter voted for the "truth" oracle level.
function reclaim(address sender, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
return reclaim_v2(sender, coin);
}
function reclaim_v2(address sender, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
Epoch storage epoch = epochs_[(epoch_id_v2_ - 2) % 3];
require(epoch.phase_v2 == Phase.RECLAIM, "rc1");
if (epoch.commits[sender].epoch_id != epoch_id_v2_ - 2){
// The corresponding commit was not found.
return (0, 0);
}
// One voter can reclaim only once per phase.
if (epoch.commits[sender].phase != Phase.REVEAL) {
return (0, 0);
}
epoch.commits[sender].phase = Phase.RECLAIM;
uint deposit = epoch.commits[sender].deposit;
uint oracle_level = epoch.commits[sender].oracle_level;
if (oracle_level == LEVEL_MAX) {
return (0, 0);
}
require(0 <= oracle_level && oracle_level < LEVEL_MAX, "rc2");
if (!epoch.votes[oracle_level].should_reclaim_v2) {
return (0, 0);
}
require(epoch.votes[oracle_level].count_v2 > 0, "rc3");
// Reclaim the deposited coins.
coin.move(epoch.deposit_account_v2, sender, deposit);
uint reward = 0;
if (epoch.votes[oracle_level].should_reward_v2) {
// The voter who voted for the "truth" level can receive the reward.
//
// The PROPORTIONAL_REWARD_RATE of the reward is distributed to the
// voters in proportion to the coins they deposited. This incentivizes
// voters who have more coins (and thus have more power on determining
// the "truth" level) to join the oracle.
//
// The rest of the reward is distributed to the voters evenly. This
// incentivizes more voters (including new voters) to join the oracle.
if (epoch.votes[oracle_level].deposit_v2 > 0) {
reward += (uint(PROPORTIONAL_REWARD_RATE) * epoch.reward_total_v2 *
deposit) /
(uint(100) * epoch.votes[oracle_level].deposit_v2);
}
reward += ((uint(100) - PROPORTIONAL_REWARD_RATE) *
epoch.reward_total_v2) /
(uint(100) * epoch.votes[oracle_level].count_v2);
coin.move(epoch.reward_account_v2, sender, reward);
}
emit ReclaimEvent(sender, epoch_id_v2_, deposit, reward);
return (deposit, reward);
}
// Advance to the next phase. COMMIT => REVEAL, REVEAL => RECLAIM,
// RECLAIM => COMMIT.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// None.
function advance(JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
return advance_v2(coin);
}
function advance_v2(JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
// Advance the phase.
epoch_id_v2_ += 1;
epoch_id_ += 1;
// Step 1: Move the commit phase to the reveal phase.
Epoch storage epoch = epochs_[(epoch_id_v2_ - 1) % 3];
require(epoch.phase_v2 == Phase.COMMIT, "ad1");
epoch.phase_v2 = Phase.REVEAL;
// Step 2: Move the reveal phase to the reclaim phase.
epoch = epochs_[(epoch_id_v2_ - 2) % 3];
require(epoch.phase_v2 == Phase.REVEAL, "ad2");
epoch.phase_v2 = Phase.RECLAIM;
// The "truth" level is set to the mode of the weighted majority votes.
uint mode_level = getModeLevel();
if (0 <= mode_level && mode_level < LEVEL_MAX) {
uint deposit_revealed = 0;
uint deposit_to_reclaim = 0;
for (uint level = 0; level < LEVEL_MAX; level++) {
require(epoch.votes[level].should_reclaim_v2 == false, "ad3");
require(epoch.votes[level].should_reward_v2 == false, "ad4");
deposit_revealed += epoch.votes[level].deposit_v2;
if ((mode_level < RECLAIM_THRESHOLD ||
mode_level - RECLAIM_THRESHOLD <= level) &&
level <= mode_level + RECLAIM_THRESHOLD) {
// Voters who voted for the oracle levels in [mode_level -
// reclaim_threshold, mode_level + reclaim_threshold] are eligible
// to reclaim their deposited coins. Other voters lose their deposited
// coins.
epoch.votes[level].should_reclaim_v2 = true;
deposit_to_reclaim += epoch.votes[level].deposit_v2;
}
}
// Voters who voted for the "truth" level are eligible to receive the
// reward.
epoch.votes[mode_level].should_reward_v2 = true;
// Note: |deposit_revealed| is equal to
// |balanceOf(epoch.deposit_account_v2)|
// only when all the voters who voted in the commit phase revealed
// their votes correctly in the reveal phase.
require(deposit_revealed <= coin.balanceOf(epoch.deposit_account_v2),
"ad5");
require(deposit_to_reclaim <= coin.balanceOf(epoch.deposit_account_v2),
"ad6");
// The lost coins are moved to the reward account.
coin.move(
epoch.deposit_account_v2,
epoch.reward_account_v2,
coin.balanceOf(epoch.deposit_account_v2) - deposit_to_reclaim);
}
// Move the collected tax to the reward account.
address tax_account = coin.tax_account_v2_();
uint tax = coin.balanceOf(tax_account);
coin.move(tax_account, epoch.reward_account_v2, tax);
// Set the total amount of the reward.
epoch.reward_total_v2 = coin.balanceOf(epoch.reward_account_v2);
// Step 3: Move the reclaim phase to the commit phase.
uint epoch_index = epoch_id_v2_ % 3;
epoch = epochs_[epoch_index];
require(epoch.phase_v2 == Phase.RECLAIM, "ad7");
uint burned = coin.balanceOf(epoch.deposit_account_v2) +
coin.balanceOf(epoch.reward_account_v2);
// Burn the remaining deposited coins.
coin.burn(epoch.deposit_account_v2, coin.balanceOf(
epoch.deposit_account_v2));
// Burn the remaining reward.
coin.burn(epoch.reward_account_v2, coin.balanceOf(epoch.reward_account_v2));
// Initialize the Epoch object for the next commit phase.
//
// |epoch.commits_| cannot be cleared due to the restriction of Solidity.
// |epoch_id_| ensures the stale commit entries are not misused.
for (uint level = 0; level < LEVEL_MAX; level++) {
epoch.votes[level] = Vote(0, 0, false, false, false, false, 0, 0);
}
// Regenerate the account addresses just in case.
require(coin.balanceOf(epoch.deposit_account_v2) == 0, "ad8");
require(coin.balanceOf(epoch.reward_account_v2) == 0, "ad9");
epoch.deposit_account_v2 =
address(uint160(uint(keccak256(abi.encode(
"deposit_v2", epoch_index, block.number)))));
epoch.reward_account_v2 =
address(uint160(uint(keccak256(abi.encode(
"reward_v2", epoch_index, block.number)))));
epoch.reward_total_v2 = 0;
epoch.phase_v2 = Phase.COMMIT;
emit AdvancePhaseEvent(epoch_id_v2_, tax, burned);
return burned;
}
// Return the oracle level that got the largest amount of deposited coins.
// In other words, return the mode of the votes weighted by the deposited
// coins.
//
// Parameters
// ----------------
// None.
//
// Returns
// ----------------
// If there are multiple modes, return the mode that has the largest votes.
// If there are multiple modes that have the largest votes, return the
// smallest mode. If there are no votes, return LEVEL_MAX.
function getModeLevel()
public onlyOwner view returns (uint) {
return getModeLevel_v2();
}
function getModeLevel_v2()
public onlyOwner view returns (uint) {
Epoch storage epoch = epochs_[(epoch_id_v2_ - 2) % 3];
require(epoch.phase_v2 == Phase.RECLAIM, "gm1");
uint mode_level = LEVEL_MAX;
uint max_deposit = 0;
uint max_count = 0;
for (uint level = 0; level < LEVEL_MAX; level++) {
if (epoch.votes[level].count_v2 > 0 &&
(mode_level == LEVEL_MAX ||
max_deposit < epoch.votes[level].deposit_v2 ||
(max_deposit == epoch.votes[level].deposit_v2 &&
max_count < epoch.votes[level].count_v2))){
max_deposit = epoch.votes[level].deposit_v2;
max_count = epoch.votes[level].count_v2;
mode_level = level;
}
}
return mode_level;
}
// Return the ownership of the JohnLawCoin contract to the ACB.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
//
// Returns
// ----------------
// None.
function revokeOwnership(JohnLawCoin_v2 coin)
public onlyOwner {
return revokeOwnership_v2(coin);
}
function revokeOwnership_v2(JohnLawCoin_v2 coin)
public onlyOwner {
coin.transferOwnership(msg.sender);
}
// Public getter: Return the Vote object at |epoch_index| and |level|.
function getVote(uint epoch_index, uint level)
public view returns (uint, uint, bool, bool) {
require(0 <= epoch_index && epoch_index <= 2, "gv1");
require(0 <= level && level < LEVEL_MAX, "gv2");
Vote memory vote = epochs_[epoch_index].votes[level];
return (vote.deposit_v2, vote.count_v2, vote.should_reclaim_v2,
vote.should_reward_v2);
}
// Public getter: Return the Commit object at |epoch_index| and |account|.
function getCommit(uint epoch_index, address account)
public view returns (bytes32, uint, uint, Phase, uint) {
require(0 <= epoch_index && epoch_index <= 2, "gc1");
Commit memory entry = epochs_[epoch_index].commits[account];
return (entry.hash, entry.deposit, entry.oracle_level,
entry.phase, entry.epoch_id);
}
// Public getter: Return the Epoch object at |epoch_index|.
function getEpoch(uint epoch_index)
public view returns (address, address, uint, Phase) {
require(0 <= epoch_index && epoch_index <= 2, "ge1");
return (epochs_[epoch_index].deposit_account_v2,
epochs_[epoch_index].reward_account_v2,
epochs_[epoch_index].reward_total_v2,
epochs_[epoch_index].phase_v2);
}
// Calculate a hash to be committed. Voters are expected to use this function
// to create a hash used in the commit phase.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |level|: The oracle level to vote.
// |salt|: The voter's salt.
//
// Returns
// ----------------
// The calculated hash value.
function encrypt(address sender, uint level, uint salt)
public pure returns (bytes32) {
return hash_v2(sender, level, salt);
}
function hash_v2(address sender, uint level, uint salt)
public pure returns (bytes32) {
return keccak256(abi.encode(sender, level, salt));
}
}
//------------------------------------------------------------------------------
// [Logging contract]
//
// The Logging contract records various metrics for analysis purpose.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract Logging_v2 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// A struct to record metrics about voting.
struct VoteLog {
uint commit_succeeded;
uint commit_failed;
uint reveal_succeeded;
uint reveal_failed;
uint reclaim_succeeded;
uint reward_succeeded;
uint deposited;
uint reclaimed;
uint rewarded;
uint new_value1;
uint new_value2;
uint new_value3;
uint new_value4;
}
// A struct to record metrics about Epoch.
struct EpochLog {
uint minted_coins;
uint burned_coins;
int coin_supply_delta;
uint total_coin_supply;
uint oracle_level;
uint current_epoch_start;
uint tax;
uint new_value1;
uint new_value2;
}
// A struct to record metrics about BondOperation.
struct BondOperationLog {
int bond_budget;
uint total_bond_supply;
uint valid_bond_supply;
uint purchased_bonds;
uint redeemed_bonds;
uint expired_bonds;
uint new_value1;
uint new_value2;
}
// A struct to record metrics about OpenMarketOperation.
struct OpenMarketOperationLog {
int coin_budget;
int exchanged_coins;
int exchanged_eth;
uint eth_balance;
uint latest_price;
uint new_value1;
uint new_value2;
}
struct AnotherLog {
uint new_value1;
uint new_value2;
uint new_value3;
uint new_value4;
}
// Attributes.
// Logs about voting.
mapping (uint => VoteLog) public vote_logs_;
// Logs about Epoch.
mapping (uint => EpochLog) public epoch_logs_;
// Logs about BondOperation.
mapping (uint => BondOperationLog) public bond_operation_logs_;
// Logs about OpenMarketOperation.
mapping (uint => OpenMarketOperationLog) public open_market_operation_logs_;
mapping (uint => AnotherLog) public another_logs_;
function upgrade()
public onlyOwner {
}
// Public getter: Return the VoteLog of |epoch_id|.
function getVoteLog(uint epoch_id)
public view returns (
uint, uint, uint, uint, uint, uint, uint, uint, uint) {
return getVoteLog_v2(epoch_id);
}
function getVoteLog_v2(uint epoch_id)
public view returns (
uint, uint, uint, uint, uint, uint, uint, uint, uint) {
VoteLog memory log = vote_logs_[epoch_id];
return (log.commit_succeeded, log.commit_failed, log.reveal_succeeded,
log.reveal_failed, log.reclaim_succeeded, log.reward_succeeded,
log.deposited, log.reclaimed, log.rewarded);
}
// Public getter: Return the EpochLog of |epoch_id|.
function getEpochLog(uint epoch_id)
public view returns (uint, uint, int, uint, uint, uint, uint) {
return getEpochLog_v2(epoch_id);
}
function getEpochLog_v2(uint epoch_id)
public view returns (uint, uint, int, uint, uint, uint, uint) {
EpochLog memory log = epoch_logs_[epoch_id];
return (log.minted_coins, log.burned_coins, log.coin_supply_delta,
log.total_coin_supply, log.oracle_level, log.current_epoch_start,
log.tax);
}
// Public getter: Return the BondOperationLog of |epoch_id|.
function getBondOperationLog(uint epoch_id)
public view returns (int, uint, uint, uint, uint, uint) {
return getBondOperationLog_v2(epoch_id);
}
function getBondOperationLog_v2(uint epoch_id)
public view returns (int, uint, uint, uint, uint, uint) {
BondOperationLog memory log = bond_operation_logs_[epoch_id];
return (log.bond_budget, log.total_bond_supply, log.valid_bond_supply,
log.purchased_bonds, log.redeemed_bonds, log.expired_bonds);
}
// Public getter: Return the OpenMarketOperationLog of |epoch_id|.
function getOpenMarketOperationLog(uint epoch_id)
public view returns (int, int, int, uint, uint) {
return getOpenMarketOperationLog_v2(epoch_id);
}
function getOpenMarketOperationLog_v2(uint epoch_id)
public view returns (int, int, int, uint, uint) {
OpenMarketOperationLog memory log = open_market_operation_logs_[epoch_id];
return (log.coin_budget, log.exchanged_coins, log.exchanged_eth,
log.eth_balance, log.latest_price);
}
// Called when the epoch is updated.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |minted|: The amount of the minted coins.
// |burned|: The amount of the burned coins.
// |delta|: The delta of the total coin supply.
// |total_coin_supply|: The total coin supply.
// |oracle_level|: ACB.oracle_level_.
// |current_epoch_start|: ACB.current_epoch_start_.
// |tax|: The amount of the tax collected in the previous epoch.
//
// Returns
// ----------------
// None.
function updateEpoch(uint epoch_id, uint minted, uint burned, int delta,
uint total_coin_supply, uint oracle_level,
uint current_epoch_start, uint tax)
public onlyOwner {
updateEpoch_v2(epoch_id, minted, burned, delta, total_coin_supply,
oracle_level, current_epoch_start, tax);
}
function updateEpoch_v2(uint epoch_id, uint minted, uint burned, int delta,
uint total_coin_supply, uint oracle_level,
uint current_epoch_start, uint tax)
public onlyOwner {
epoch_logs_[epoch_id].minted_coins = minted;
epoch_logs_[epoch_id].burned_coins = burned;
epoch_logs_[epoch_id].coin_supply_delta = delta;
epoch_logs_[epoch_id].total_coin_supply = total_coin_supply;
epoch_logs_[epoch_id].oracle_level = oracle_level;
epoch_logs_[epoch_id].current_epoch_start = current_epoch_start;
epoch_logs_[epoch_id].tax = tax;
epoch_logs_[epoch_id].new_value1 += minted;
epoch_logs_[epoch_id].new_value2 += burned;
another_logs_[epoch_id].new_value1 += minted;
another_logs_[epoch_id].new_value2 += burned;
}
// Called when BondOperation's bond budget is updated at the beginning of
// the epoch.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |bond_budget|: The bond budget.
// |total_bond_supply|: The total bond supply.
// |valid_bond_supply|: The valid bond supply.
//
// Returns
// ----------------
// None.
function updateBondBudget(uint epoch_id, int bond_budget,
uint total_bond_supply, uint valid_bond_supply)
public onlyOwner {
updateBondBudget_v2(epoch_id, bond_budget,
total_bond_supply, valid_bond_supply);
}
function updateBondBudget_v2(uint epoch_id, int bond_budget,
uint total_bond_supply, uint valid_bond_supply)
public onlyOwner {
bond_operation_logs_[epoch_id].bond_budget = bond_budget;
bond_operation_logs_[epoch_id].total_bond_supply = total_bond_supply;
bond_operation_logs_[epoch_id].valid_bond_supply = valid_bond_supply;
bond_operation_logs_[epoch_id].purchased_bonds = 0;
bond_operation_logs_[epoch_id].redeemed_bonds = 0;
bond_operation_logs_[epoch_id].expired_bonds = 0;
bond_operation_logs_[epoch_id].new_value1 = epoch_id;
bond_operation_logs_[epoch_id].new_value2 = epoch_id;
another_logs_[epoch_id].new_value1 += epoch_id;
another_logs_[epoch_id].new_value2 += epoch_id;
}
// Called when OpenMarketOperation's coin budget is updated at the beginning
// of the epoch.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |coin_budget|: The coin budget.
// |eth_balance|: The ETH balance in the EthPool.
// |latest_price|: The latest ETH / JLC price.
//
// Returns
// ----------------
// None.
function updateCoinBudget(uint epoch_id, int coin_budget,
uint eth_balance, uint latest_price)
public onlyOwner {
updateCoinBudget_v2(epoch_id, coin_budget, eth_balance, latest_price);
}
function updateCoinBudget_v2(uint epoch_id, int coin_budget,
uint eth_balance, uint latest_price)
public onlyOwner {
open_market_operation_logs_[epoch_id].coin_budget = coin_budget;
open_market_operation_logs_[epoch_id].exchanged_coins = 0;
open_market_operation_logs_[epoch_id].exchanged_eth = 0;
open_market_operation_logs_[epoch_id].eth_balance = eth_balance;
open_market_operation_logs_[epoch_id].latest_price = latest_price;
open_market_operation_logs_[epoch_id].new_value1 = epoch_id;
open_market_operation_logs_[epoch_id].new_value2 = epoch_id;
another_logs_[epoch_id].new_value1 += epoch_id;
another_logs_[epoch_id].new_value2 += epoch_id;
}
// Called when ACB.vote is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |commit_result|: Whether the commit succeeded or not.
// |reveal_result|: Whether the reveal succeeded or not.
// |deposited|: The amount of the deposited coins.
// |reclaimed|: The amount of the reclaimed coins.
// |rewarded|: The amount of the reward.
//
// Returns
// ----------------
// None.
function vote(uint epoch_id, bool commit_result, bool reveal_result,
uint deposit, uint reclaimed, uint rewarded)
public onlyOwner {
vote_v2(epoch_id, commit_result, reveal_result, deposit,
reclaimed, rewarded);
}
function vote_v2(uint epoch_id, bool commit_result, bool reveal_result,
uint deposit, uint reclaimed, uint rewarded)
public onlyOwner {
if (commit_result) {
vote_logs_[epoch_id].commit_succeeded += 1;
} else {
vote_logs_[epoch_id].commit_failed += 1;
}
if (reveal_result) {
vote_logs_[epoch_id].reveal_succeeded += 1;
} else {
vote_logs_[epoch_id].reveal_failed += 1;
}
if (reclaimed > 0) {
vote_logs_[epoch_id].reclaim_succeeded += 1;
}
if (rewarded > 0) {
vote_logs_[epoch_id].reward_succeeded += 1;
}
vote_logs_[epoch_id].deposited += deposit;
vote_logs_[epoch_id].reclaimed += reclaimed;
vote_logs_[epoch_id].rewarded += rewarded;
vote_logs_[epoch_id].new_value1 += deposit;
vote_logs_[epoch_id].new_value2 += reclaimed;
another_logs_[epoch_id].new_value1 += deposit;
another_logs_[epoch_id].new_value2 += reclaimed;
}
// Called when ACB.purchaseBonds is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |purchased_bonds|: The number of purchased bonds.
//
// Returns
// ----------------
// None.
function purchaseBonds(uint epoch_id, uint purchased_bonds)
public onlyOwner {
purchaseBonds_v2(epoch_id, purchased_bonds);
}
function purchaseBonds_v2(uint epoch_id, uint purchased_bonds)
public onlyOwner {
bond_operation_logs_[epoch_id].purchased_bonds += purchased_bonds;
bond_operation_logs_[epoch_id].new_value1 += purchased_bonds;
}
// Called when ACB.redeemBonds is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |redeemed_bonds|: The number of redeemded bonds.
// |expired_bonds|: The number of expired bonds.
//
// Returns
// ----------------
// None.
function redeemBonds(uint epoch_id, uint redeemed_bonds, uint expired_bonds)
public onlyOwner {
redeemBonds_v2(epoch_id, redeemed_bonds, expired_bonds);
}
function redeemBonds_v2(uint epoch_id, uint redeemed_bonds,
uint expired_bonds)
public onlyOwner {
bond_operation_logs_[epoch_id].redeemed_bonds += redeemed_bonds;
bond_operation_logs_[epoch_id].expired_bonds += expired_bonds;
bond_operation_logs_[epoch_id].new_value1 += redeemed_bonds;
bond_operation_logs_[epoch_id].new_value2 += expired_bonds;
}
// Called when ACB.purchaseCoins is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |eth_amount|: The amount of ETH exchanged.
// |coin_amount|: The amount of coins exchanged.
//
// Returns
// ----------------
// None.
function purchaseCoins(uint epoch_id, uint eth_amount, uint coin_amount)
public onlyOwner {
purchaseCoins_v2(epoch_id, eth_amount, coin_amount);
}
function purchaseCoins_v2(uint epoch_id, uint eth_amount, uint coin_amount)
public onlyOwner {
open_market_operation_logs_[epoch_id].exchanged_eth +=
eth_amount.toInt256();
open_market_operation_logs_[epoch_id].exchanged_coins +=
coin_amount.toInt256();
open_market_operation_logs_[epoch_id].new_value1 += eth_amount;
open_market_operation_logs_[epoch_id].new_value2 += coin_amount;
}
// Called when ACB.sellCoins is called.
//
// Parameters
// ----------------
// |epoch_id|: The epoch ID.
// |eth_amount|: The amount of ETH exchanged.
// |coin_amount|: The amount of coins exchanged.
//
// Returns
// ----------------
// None.
function sellCoins(uint epoch_id, uint eth_amount, uint coin_amount)
public onlyOwner {
sellCoins_v2(epoch_id, eth_amount, coin_amount);
}
function sellCoins_v2(uint epoch_id, uint eth_amount, uint coin_amount)
public onlyOwner {
open_market_operation_logs_[epoch_id].exchanged_eth -=
eth_amount.toInt256();
open_market_operation_logs_[epoch_id].exchanged_coins -=
coin_amount.toInt256();
open_market_operation_logs_[epoch_id].new_value1 += eth_amount;
open_market_operation_logs_[epoch_id].new_value2 += coin_amount;
}
}
//------------------------------------------------------------------------------
// [BondOperation contract]
//
// The BondOperation contract increases / decreases the total coin supply by
// redeeming / issuing bonds. The bond budget is updated by the ACB every epoch.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract BondOperation_v2 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public BOND_PRICE;
uint public BOND_REDEMPTION_PRICE;
uint public BOND_REDEMPTION_PERIOD;
uint public BOND_REDEEMABLE_PERIOD;
// Attributes. See the comment in initialize().
JohnLawBond public bond_;
int public bond_budget_;
JohnLawBond_v2 public bond_v2_;
int public bond_budget_v2_;
// Events.
event IncreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint issued_bonds, uint redemption_epoch);
event DecreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint redeemed_bonds, uint expired_bonds);
event UpdateBondBudgetEvent(uint indexed epoch_id, int delta,
int bond_budget, uint mint);
function upgrade(JohnLawBond_v2 bond)
public onlyOwner {
bond_v2_ = bond;
bond_budget_v2_ = bond_budget_;
bond_v2_.upgrade();
}
// Deprecate the contract.
function deprecate()
public onlyOwner {
bond_v2_.transferOwnership(msg.sender);
}
// Increase the total bond supply by issuing bonds.
//
// Parameters
// ----------------
// |count|: The number of bonds to be issued.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// The redemption epoch of the issued bonds if it succeeds. 0 otherwise.
function increaseBondSupply(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
return increaseBondSupply_v2(sender, count, epoch_id, coin);
}
function increaseBondSupply_v2(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
require(count > 0, "BondOperation: You must purchase at least one bond.");
require(bond_budget_v2_ >= count.toInt256(),
"BondOperation: The bond budget is not enough.");
uint amount = BOND_PRICE * count;
require(coin.balanceOf(sender) >= amount,
"BondOperation: Your coin balance is not enough.");
// Set the redemption epoch of the bonds.
uint redemption_epoch = epoch_id + BOND_REDEMPTION_PERIOD;
// Issue new bonds.
bond_v2_.mint(sender, redemption_epoch, count);
bond_budget_v2_ -= count.toInt256();
require(bond_budget_v2_ >= 0, "pb1");
require(bond_v2_.balanceOf(sender, redemption_epoch) > 0, "pb2");
// Burn the corresponding coins.
coin.burn(sender, amount);
bond_budget_ = bond_budget_v2_;
emit IncreaseBondSupplyEvent(sender, epoch_id, count, redemption_epoch);
return redemption_epoch;
}
// Decrease the total bond supply by redeeming bonds.
//
// Parameters
// ----------------
// |redemption_epochs|: An array of bonds to be redeemed. The bonds are
// identified by their redemption epochs.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// A tuple of two values:
// - The number of redeemed bonds.
// - The number of expired bonds.
function decreaseBondSupply(address sender, uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
return decreaseBondSupply_v2(sender, redemption_epochs, epoch_id, coin);
}
function decreaseBondSupply_v2(address sender,
uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
uint redeemed_bonds = 0;
uint expired_bonds = 0;
for (uint i = 0; i < redemption_epochs.length; i++) {
uint redemption_epoch = redemption_epochs[i];
uint count = bond_v2_.balanceOf(sender, redemption_epoch);
if (epoch_id < redemption_epoch) {
// If the bonds have not yet hit their redemption epoch, the
// BondOperation accepts the redemption as long as |bond_budget_| is
// negative.
if (bond_budget_v2_ >= 0) {
continue;
}
if (count > (-bond_budget_v2_).toUint256()) {
count = (-bond_budget_v2_).toUint256();
}
bond_budget_v2_ += count.toInt256();
}
if (epoch_id < redemption_epoch + BOND_REDEEMABLE_PERIOD) {
// If the bonds are not expired, mint the corresponding coins to the
// sender account.
uint amount = count * BOND_REDEMPTION_PRICE;
coin.mint(sender, amount);
redeemed_bonds += count;
} else {
expired_bonds += count;
}
// Burn the redeemed / expired bonds.
bond_v2_.burn(sender, redemption_epoch, count);
}
bond_budget_ = bond_budget_v2_;
emit DecreaseBondSupplyEvent(sender, epoch_id,
redeemed_bonds, expired_bonds);
return (redeemed_bonds, expired_bonds);
}
// Update the bond budget to increase or decrease the total coin supply.
//
// Parameters
// ----------------
// |delta|: The target increase or decrease of the total coin supply.
// |epoch_id|: The current epoch ID.
//
// Returns
// ----------------
// The amount of coins that cannot be increased by adjusting the bond budget
// and thus need to be newly minted.
function updateBondBudget(int delta, uint epoch_id)
public onlyOwner returns (uint) {
return updateBondBudget_v2(delta, epoch_id);
}
function updateBondBudget_v2(int delta, uint epoch_id)
public onlyOwner returns (uint) {
uint mint = 0;
uint bond_supply = validBondSupply(epoch_id);
if (delta == 0) {
// No change in the total coin supply.
bond_budget_v2_ = 0;
} else if (delta > 0) {
// Increase the total coin supply.
uint count = delta.toUint256() / BOND_REDEMPTION_PRICE;
if (count <= bond_supply) {
// If there are sufficient bonds to redeem, increase the total coin
// supply by redeeming the bonds.
bond_budget_v2_ = -count.toInt256();
} else {
// Otherwise, redeem all the issued bonds.
bond_budget_v2_ = -bond_supply.toInt256();
// The remaining coins need to be newly minted.
mint = (count - bond_supply) * BOND_REDEMPTION_PRICE;
}
require(bond_budget_v2_ <= 0, "cs1");
} else {
// Issue new bonds to decrease the total coin supply.
bond_budget_v2_ = -delta / BOND_PRICE.toInt256();
require(bond_budget_v2_ >= 0, "cs2");
}
bond_budget_ = bond_budget_v2_;
require(bond_supply.toInt256() + bond_budget_v2_ >= 0, "cs3");
emit UpdateBondBudgetEvent(epoch_id, delta, bond_budget_v2_, mint);
return mint;
}
// Public getter: Return the valid bond supply; i.e., the total supply of
// not-yet-expired bonds.
function validBondSupply(uint epoch_id)
public view returns (uint) {
return validBondSupply_v2(epoch_id);
}
function validBondSupply_v2(uint epoch_id)
public view returns (uint) {
uint count = 0;
for (uint redemption_epoch =
(epoch_id > BOND_REDEEMABLE_PERIOD ?
epoch_id - BOND_REDEEMABLE_PERIOD + 1 : 0);
// The previous versions of the smart contract might have used a larger
// BOND_REDEMPTION_PERIOD. Add 20 to look up all the redemption
// epochs that might have set in the previous versions.
redemption_epoch <= epoch_id + BOND_REDEMPTION_PERIOD + 20;
redemption_epoch++) {
count += bond_v2_.bondSupplyAt(redemption_epoch);
}
return count;
}
// Return the ownership of the JohnLawCoin contract to the ACB.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
//
// Returns
// ----------------
// None.
function revokeOwnership(JohnLawCoin_v2 coin)
public onlyOwner {
return revokeOwnership_v2(coin);
}
function revokeOwnership_v2(JohnLawCoin_v2 coin)
public onlyOwner {
coin.transferOwnership(msg.sender);
}
}
//------------------------------------------------------------------------------
// [OpenMarketOperation contract]
//
// The OpenMarketOperation contract increases / decreases the total coin supply
// by purchasing / selling ETH from the open market. The price between JLC and
// ETH is determined by a Dutch auction.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract OpenMarketOperation_v2 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public PRICE_CHANGE_INTERVAL;
uint public PRICE_CHANGE_PERCENTAGE;
uint public PRICE_CHANGE_MAX;
uint public PRICE_MULTIPLIER;
// Attributes. See the comment in initialize().
uint public latest_price_;
bool public latest_price_updated_;
uint public start_price_;
int public coin_budget_;
uint public latest_price_v2_;
bool public latest_price_updated_v2_;
uint public start_price_v2_;
int public coin_budget_v2_;
// Events.
event IncreaseCoinSupplyEvent(uint requested_eth_amount, uint elapsed_time,
uint eth_amount, uint coin_amount);
event DecreaseCoinSupplyEvent(uint requested_coin_amount, uint elapsed_time,
uint eth_balance, uint eth_amount,
uint coin_amount);
event UpdateCoinBudgetEvent(int coin_budget);
function upgrade()
public onlyOwner {
latest_price_v2_ = latest_price_;
latest_price_updated_v2_ = latest_price_updated_;
start_price_v2_ = start_price_;
coin_budget_v2_ = coin_budget_;
}
// Increase the total coin supply by purchasing ETH from the sender account.
// This method returns the amount of JLC and ETH to be exchanged. The actual
// change to the total coin supply and the ETH pool is made by the ACB.
//
// Parameters
// ----------------
// |requested_eth_amount|: The amount of ETH the sender is willing to pay.
// |elapsed_time|: The elapsed seconds from the current epoch start.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH to be exchanged. This can be smaller than
// |requested_eth_amount| when the open market operation does not have
// enough coin budget.
// - The amount of JLC to be exchanged.
function increaseCoinSupply(uint requested_eth_amount, uint elapsed_time)
public onlyOwner returns (uint, uint) {
return increaseCoinSupply_v2(requested_eth_amount, elapsed_time);
}
function increaseCoinSupply_v2(uint requested_eth_amount, uint elapsed_time)
public onlyOwner returns (uint, uint) {
require(coin_budget_v2_ > 0,
"OpenMarketOperation: The coin budget must be positive.");
// Calculate the amount of JLC and ETH to be exchanged.
uint price = getCurrentPrice(elapsed_time);
uint coin_amount = requested_eth_amount / price;
if (coin_amount > coin_budget_v2_.toUint256()) {
coin_amount = coin_budget_v2_.toUint256();
}
uint eth_amount = coin_amount * price;
if (coin_amount > 0) {
latest_price_v2_ = price;
latest_price_updated_v2_ = true;
}
coin_budget_v2_ -= coin_amount.toInt256();
require(coin_budget_v2_ >= 0, "ic1");
require(eth_amount <= requested_eth_amount, "ic2");
emit IncreaseCoinSupplyEvent(requested_eth_amount, elapsed_time,
eth_amount, coin_amount);
latest_price_ = latest_price_v2_;
latest_price_updated_ = latest_price_updated_v2_;
start_price_ = start_price_v2_;
coin_budget_ = coin_budget_v2_;
return (eth_amount, coin_amount);
}
// Decrease the total coin supply by selling ETH to the sender account.
// This method returns the amount of JLC and ETH to be exchanged. The actual
// change to the total coin supply and the ETH pool is made by the ACB.
//
// Parameters
// ----------------
// |requested_coin_amount|: The amount of JLC the sender is willing to pay.
// |elapsed_time|: The elapsed seconds from the current epoch start.
// |eth_balance|: The ETH balance in the EthPool.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH to be exchanged.
// - The amount of JLC to be exchanged. This can be smaller than
// |requested_coin_amount| when the open market operation does not have
// enough ETH in the pool.
function decreaseCoinSupply(uint requested_coin_amount, uint elapsed_time,
uint eth_balance)
public onlyOwner returns (uint, uint) {
return decreaseCoinSupply_v2(requested_coin_amount, elapsed_time,
eth_balance);
}
function decreaseCoinSupply_v2(uint requested_coin_amount, uint elapsed_time,
uint eth_balance)
public onlyOwner returns (uint, uint) {
require(coin_budget_v2_ < 0,
"OpenMarketOperation: The coin budget must be negative.");
// Calculate the amount of JLC and ETH to be exchanged.
uint price = getCurrentPrice(elapsed_time);
uint coin_amount = requested_coin_amount;
if (coin_amount >= (-coin_budget_v2_).toUint256()) {
coin_amount = (-coin_budget_v2_).toUint256();
}
uint eth_amount = coin_amount * price;
if (eth_amount >= eth_balance) {
eth_amount = eth_balance;
}
coin_amount = eth_amount / price;
if (coin_amount > 0) {
latest_price_v2_ = price;
latest_price_updated_v2_ = true;
}
coin_budget_v2_ += coin_amount.toInt256();
require(coin_budget_v2_ <= 0, "dc1");
require(coin_amount <= requested_coin_amount, "dc2");
emit DecreaseCoinSupplyEvent(requested_coin_amount, elapsed_time,
eth_balance, eth_amount, coin_amount);
latest_price_ = latest_price_v2_;
latest_price_updated_ = latest_price_updated_v2_;
start_price_ = start_price_v2_;
coin_budget_ = coin_budget_v2_;
return (eth_amount, coin_amount);
}
// Return the current price in the Dutch auction.
//
// Parameters
// ----------------
// |elapsed_time|: The elapsed seconds from the current epoch start.
//
// Returns
// ----------------
// The current price.
function getCurrentPrice(uint elapsed_time)
public view returns (uint) {
return getCurrentPrice_v2(elapsed_time);
}
function getCurrentPrice_v2(uint elapsed_time)
public view returns (uint) {
if (coin_budget_v2_ > 0) {
uint price = start_price_v2_;
for (uint i = 0;
i < elapsed_time / PRICE_CHANGE_INTERVAL && i < PRICE_CHANGE_MAX;
i++) {
price = price * (100 - PRICE_CHANGE_PERCENTAGE) / 100;
}
if (price == 0) {
price = 1;
}
return price;
} else if (coin_budget_v2_ < 0) {
uint price = start_price_v2_;
for (uint i = 0;
i < elapsed_time / PRICE_CHANGE_INTERVAL && i < PRICE_CHANGE_MAX;
i++) {
price = price * (100 + PRICE_CHANGE_PERCENTAGE) / 100;
}
return price;
}
return 0;
}
// Update the coin budget. The coin budget indicates how many coins should
// be added to / removed from the total coin supply; i.e., the amount of JLC
// to be sold / purchased by the open market operation. The ACB calls the
// method at the beginning of each epoch.
//
// Parameters
// ----------------
// |coin_budget|: The coin budget.
//
// Returns
// ----------------
// None.
function updateCoinBudget(int coin_budget)
public onlyOwner {
updateCoinBudget_v2(coin_budget);
}
function updateCoinBudget_v2(int coin_budget)
public onlyOwner {
if (latest_price_updated_v2_ == false) {
if (coin_budget_v2_ > 0) {
// If no exchange was observed in the previous epoch, the price setting
// was too high. Lower the price.
latest_price_v2_ = latest_price_v2_ / PRICE_MULTIPLIER + 1;
} else if (coin_budget_v2_ < 0) {
// If no exchange was observed in the previous epoch, the price setting
// was too low. Raise the price.
latest_price_v2_ = latest_price_v2_ * PRICE_MULTIPLIER;
}
}
coin_budget_v2_ = coin_budget;
latest_price_updated_v2_ = false;
require(latest_price_v2_ > 0, "uc1");
if (coin_budget_v2_ > 0) {
start_price_v2_ = latest_price_v2_ * PRICE_MULTIPLIER;
} else if (coin_budget_v2_ == 0) {
start_price_v2_ = 0;
} else {
start_price_v2_ = latest_price_v2_ / PRICE_MULTIPLIER + 1;
}
emit UpdateCoinBudgetEvent(coin_budget_v2_);
latest_price_ = latest_price_v2_;
latest_price_updated_ = latest_price_updated_v2_;
start_price_ = start_price_v2_;
coin_budget_ = coin_budget_v2_;
}
}
//------------------------------------------------------------------------------
// [EthPool contract]
//
// The EthPool contract stores ETH for the open market operation.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract EthPool_v2 is OwnableUpgradeable {
function upgrade()
public onlyOwner {
}
// Increase ETH.
function increaseEth()
public onlyOwner payable {
increaseEth_v2();
}
function increaseEth_v2()
public onlyOwner payable {
}
// Decrease |eth_amount| ETH and send it to the |receiver|.
function decreaseEth(address receiver, uint eth_amount)
public onlyOwner {
decreaseEth_v2(receiver, eth_amount);
}
function decreaseEth_v2(address receiver, uint eth_amount)
public onlyOwner {
require(address(this).balance >= eth_amount, "de1");
(bool success,) =
payable(receiver).call{value: eth_amount}("");
require(success, "de2");
}
}
//------------------------------------------------------------------------------
// [ACB contract]
//
// The ACB stabilizes the USD / JLC exchange rate to 1.0 with algorithmically
// defined monetary policies:
//
// 1. The ACB obtains the exchange rate from the oracle.
// 2. If the exchange rate is 1.0, the ACB does nothing.
// 3. If the exchange rate is higher than 1.0, the ACB increases the total coin
// supply by redeeming issued bonds (regardless of their redemption dates).
// If that is not enough to supply sufficient coins, the ACB performs an open
// market operation to sell JLC and purchase ETH to increase the total coin
// supply.
// 4. If the exchange rate is lower than 1.0, the ACB decreases the total coin
// supply by issuing new bonds. If the exchange rate drops down to 0.6, the
// ACB performs an open market operation to sell ETH and purchase JLC to
// decrease the total coin supply.
//
// Permission: All the methods are public. No one (including the genesis
// account) is privileged to influence the monetary policies of the ACB. The ACB
// is fully decentralized and there is truly no gatekeeper. The only exceptions
// are a few methods the genesis account may use to upgrade the smart contracts
// to fix bugs during a development phase.
//------------------------------------------------------------------------------
contract ACB_v2 is OwnableUpgradeable, PausableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
bytes32 public constant NULL_HASH = 0;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint[] public LEVEL_TO_EXCHANGE_RATE;
uint public EXCHANGE_RATE_DIVISOR;
uint public EPOCH_DURATION;
uint public DEPOSIT_RATE;
uint public DAMPING_FACTOR;
// Used only in testing. This cannot be put in a derived contract due to
// a restriction of @openzeppelin/truffle-upgrades.
uint public _timestamp_for_testing;
// Attributes. See the comment in initialize().
JohnLawCoin public coin_;
Oracle public oracle_;
BondOperation public bond_operation_;
OpenMarketOperation public open_market_operation_;
EthPool public eth_pool_;
Logging public logging_;
uint public oracle_level_;
uint public current_epoch_start_;
JohnLawCoin_v2 public coin_v2_;
Oracle_v2 public oracle_v2_;
BondOperation_v2 public bond_operation_v2_;
OpenMarketOperation_v2 public open_market_operation_v2_;
EthPool_v2 public eth_pool_v2_;
Logging_v2 public logging_v2_;
uint public oracle_level_v2_;
uint public current_epoch_start_v2_;
// Events.
event PayableEvent(address indexed sender, uint value);
event UpdateEpochEvent(uint epoch_id, uint current_epoch_start, uint tax,
uint burned, int delta, uint mint);
event VoteEvent(address indexed sender, uint indexed epoch_id,
bytes32 hash, uint oracle_level, uint salt,
bool commit_result, bool reveal_result,
uint deposited, uint reclaimed, uint rewarded,
bool epoch_updated);
event PurchaseBondsEvent(address indexed sender, uint indexed epoch_id,
uint purchased_bonds, uint redemption_epoch);
event RedeemBondsEvent(address indexed sender, uint indexed epoch_id,
uint redeemed_bonds, uint expired_bonds);
event PurchaseCoinsEvent(address indexed sender, uint requested_eth_amount,
uint eth_amount, uint coin_amount);
event SellCoinsEvent(address indexed sender, uint requested_coin_amount,
uint eth_amount, uint coin_amount);
function upgrade(JohnLawCoin_v2 coin, JohnLawBond_v2 bond,
Oracle_v2 oracle, BondOperation_v2 bond_operation,
OpenMarketOperation_v2 open_market_operation,
EthPool_v2 eth_pool,
Logging_v2 logging)
public onlyOwner {
coin_v2_ = coin;
oracle_v2_ = oracle;
bond_operation_v2_ = bond_operation;
open_market_operation_v2_ = open_market_operation;
eth_pool_v2_ = eth_pool;
oracle_level_v2_ = oracle_level_;
current_epoch_start_v2_ = current_epoch_start_;
logging_v2_ = logging;
coin_v2_.upgrade();
bond_operation_v2_.upgrade(bond);
open_market_operation_v2_.upgrade();
eth_pool_v2_.upgrade();
oracle_v2_.upgrade();
logging_v2_.upgrade();
}
// Deprecate the ACB. Only the genesis account can call this method.
function deprecate()
public onlyOwner {
coin_v2_.transferOwnership(msg.sender);
oracle_v2_.transferOwnership(msg.sender);
bond_operation_v2_.transferOwnership(msg.sender);
open_market_operation_v2_.transferOwnership(msg.sender);
eth_pool_v2_.transferOwnership(msg.sender);
logging_v2_.transferOwnership(msg.sender);
}
// Pause the ACB in emergency cases. Only the genesis account can call this
// method.
function pause()
public onlyOwner {
if (!paused()) {
_pause();
}
coin_v2_.pause();
}
// Unpause the ACB. Only the genesis account can call this method.
function unpause()
public onlyOwner {
if (paused()) {
_unpause();
}
coin_v2_.unpause();
}
// Payable fallback to receive and store ETH. Give us tips :)
fallback() external payable {
require(msg.data.length == 0, "fb1");
emit PayableEvent(msg.sender, msg.value);
}
receive() external payable {
emit PayableEvent(msg.sender, msg.value);
}
// Withdraw the tips. Only the genesis account can call this method.
function withdrawTips()
public whenNotPaused onlyOwner {
(bool success,) =
payable(msg.sender).call{value: address(this).balance}("");
require(success, "wt1");
}
// A struct to pack local variables. This is needed to avoid a stack-too-deep
// error in Solidity.
struct VoteResult {
uint epoch_id;
bool epoch_updated;
bool reveal_result;
bool commit_result;
uint deposited;
uint reclaimed;
uint rewarded;
}
// Vote for the exchange rate. The voter can commit a vote to the current
// epoch N, reveal their vote in the epoch N-1, and reclaim the deposited
// coins and get a reward for their vote in the epoch N-2 at the same time.
//
// Parameters
// ----------------
// |hash|: The hash to be committed in the current epoch N. Specify
// ACB.NULL_HASH if you do not want to commit and only want to reveal and
// reclaim previous votes.
// |oracle_level|: The oracle level you voted for in the epoch N-1.
// |salt|: The salt you used in the epoch N-1.
//
// Returns
// ----------------
// A tuple of six values:
// - boolean: Whether the commit succeeded or not.
// - boolean: Whether the reveal succeeded or not.
// - uint: The amount of the deposited coins.
// - uint: The amount of the reclaimed coins.
// - uint: The amount of the reward.
// - boolean: Whether this vote updated the epoch.
function vote(bytes32 hash, uint oracle_level,
uint salt)
public whenNotPaused returns (bool, bool, uint, uint, uint, bool) {
return vote_v2(hash, oracle_level, salt);
}
function vote_v2(bytes32 hash, uint oracle_level,
uint salt)
public whenNotPaused returns (bool, bool, uint, uint, uint, bool) {
VoteResult memory result;
result.epoch_id = oracle_v2_.epoch_id_();
result.epoch_updated = false;
if (getTimestamp() >= current_epoch_start_v2_ + EPOCH_DURATION) {
// Start a new epoch.
result.epoch_updated = true;
result.epoch_id += 1;
current_epoch_start_v2_ = getTimestamp();
current_epoch_start_ = current_epoch_start_v2_;
// Advance to the next epoch. Provide the |tax| coins to the oracle
// as a reward.
uint tax = coin_v2_.balanceOf(coin_v2_.tax_account_v2_());
coin_v2_.transferOwnership(address(oracle_v2_));
uint burned = oracle_v2_.advance(coin_v2_);
oracle_v2_.revokeOwnership(coin_v2_);
// Reset the tax account address just in case.
coin_v2_.resetTaxAccount();
require(coin_v2_.balanceOf(coin_v2_.tax_account_v2_()) == 0, "vo1");
int delta = 0;
oracle_level_ = oracle_v2_.getModeLevel();
if (oracle_level_ != oracle_v2_.LEVEL_MAX()) {
require(0 <= oracle_level_ && oracle_level_ < oracle_v2_.LEVEL_MAX(),
"vo2");
// Translate the oracle level to the exchange rate.
uint exchange_rate = LEVEL_TO_EXCHANGE_RATE[oracle_level_];
// Calculate the amount of coins to be minted or burned based on the
// Quantity Theory of Money. If the exchange rate is 1.1 (i.e., 1 coin
// = 1.1 USD), the total coin supply is increased by 10%. If the
// exchange rate is 0.8 (i.e., 1 coin = 0.8 USD), the total coin supply
// is decreased by 20%.
delta = coin_v2_.totalSupply().toInt256() *
(int(exchange_rate) - int(EXCHANGE_RATE_DIVISOR)) /
int(EXCHANGE_RATE_DIVISOR);
// To avoid increasing or decreasing too many coins in one epoch,
// multiply the damping factor.
delta = delta * int(DAMPING_FACTOR) / 100;
}
// Update the bond budget.
uint mint =
bond_operation_v2_.updateBondBudget(delta, result.epoch_id);
// Update the coin budget.
if (oracle_level_ == 0 && delta < 0) {
require(mint == 0, "vo3");
open_market_operation_v2_.updateCoinBudget(delta);
} else {
open_market_operation_v2_.updateCoinBudget(mint.toInt256());
}
logging_v2_.updateEpoch(
result.epoch_id, mint, burned, delta, coin_v2_.totalSupply(),
oracle_level_, current_epoch_start_v2_, tax);
logging_v2_.updateBondBudget(
result.epoch_id, bond_operation_v2_.bond_budget_v2_(),
bond_operation_v2_.bond_v2_().totalSupply(),
bond_operation_v2_.validBondSupply(result.epoch_id));
logging_v2_.updateCoinBudget(
result.epoch_id, open_market_operation_v2_.coin_budget_v2_(),
address(eth_pool_).balance,
open_market_operation_v2_.latest_price_());
emit UpdateEpochEvent(result.epoch_id, current_epoch_start_v2_,
tax, burned, delta, mint);
}
coin_v2_.transferOwnership(address(oracle_v2_));
// Commit.
//
// The voter needs to deposit the DEPOSIT_RATE percentage of their coin
// balance.
result.deposited = coin_v2_.balanceOf(msg.sender) * DEPOSIT_RATE / 100;
if (hash == 0) {
result.deposited = 0;
}
result.commit_result = oracle_v2_.commit(
msg.sender, hash, result.deposited, coin_v2_);
if (!result.commit_result) {
result.deposited = 0;
}
// Reveal.
result.reveal_result = oracle_v2_.reveal(msg.sender, oracle_level, salt);
// Reclaim.
(result.reclaimed, result.rewarded) =
oracle_v2_.reclaim(msg.sender, coin_v2_);
oracle_v2_.revokeOwnership(coin_v2_);
logging_v2_.vote(result.epoch_id, result.commit_result,
result.reveal_result, result.deposited,
result.reclaimed, result.rewarded);
emit VoteEvent(
msg.sender, result.epoch_id, hash, oracle_level, salt,
result.commit_result, result.reveal_result, result.deposited,
result.reclaimed, result.rewarded, result.epoch_updated);
return (result.commit_result, result.reveal_result, result.deposited,
result.reclaimed, result.rewarded, result.epoch_updated);
}
// Purchase bonds.
//
// Parameters
// ----------------
// |count|: The number of bonds to purchase.
//
// Returns
// ----------------
// The redemption epoch of the purchased bonds.
function purchaseBonds(uint count)
public whenNotPaused returns (uint) {
return purchaseBonds_v2(count);
}
function purchaseBonds_v2(uint count)
public whenNotPaused returns (uint) {
uint epoch_id = oracle_v2_.epoch_id_();
coin_v2_.transferOwnership(address(bond_operation_v2_));
uint redemption_epoch =
bond_operation_v2_.increaseBondSupply(address(msg.sender), count,
epoch_id, coin_v2_);
bond_operation_v2_.revokeOwnership(coin_v2_);
logging_v2_.purchaseBonds(epoch_id, count);
emit PurchaseBondsEvent(address(msg.sender), epoch_id,
count, redemption_epoch);
return redemption_epoch;
}
// Redeem bonds.
//
// Parameters
// ----------------
// |redemption_epochs|: An array of bonds to be redeemed. The bonds are
// identified by their redemption epochs.
//
// Returns
// ----------------
// The number of successfully redeemed bonds.
function redeemBonds(uint[] memory redemption_epochs)
public whenNotPaused returns (uint) {
return redeemBonds_v2(redemption_epochs);
}
function redeemBonds_v2(uint[] memory redemption_epochs)
public whenNotPaused returns (uint) {
uint epoch_id = oracle_v2_.epoch_id_();
coin_v2_.transferOwnership(address(bond_operation_v2_));
(uint redeemed_bonds, uint expired_bonds) =
bond_operation_v2_.decreaseBondSupply(
address(msg.sender), redemption_epochs, epoch_id, coin_v2_);
bond_operation_v2_.revokeOwnership(coin_v2_);
logging_v2_.redeemBonds(epoch_id, redeemed_bonds, expired_bonds);
emit RedeemBondsEvent(address(msg.sender), epoch_id,
redeemed_bonds, expired_bonds);
return redeemed_bonds;
}
// Pay ETH and purchase JLC from the open market operation.
//
// Parameters
// ----------------
// The sender needs to pay |requested_eth_amount| ETH.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH the sender paid. This value can be smaller than
// |requested_eth_amount| when the open market operation does not have enough
// coin budget. The remaining ETH is returned to the sender's wallet.
// - The amount of JLC the sender purchased.
function purchaseCoins()
public whenNotPaused payable returns (uint, uint) {
uint requested_eth_amount = msg.value;
uint elapsed_time = getTimestamp() - current_epoch_start_v2_;
// Calculate the amount of ETH and JLC to be exchanged.
(uint eth_amount, uint coin_amount) =
open_market_operation_v2_.increaseCoinSupply(
requested_eth_amount, elapsed_time);
coin_v2_.mint(msg.sender, coin_amount);
require(address(this).balance >= requested_eth_amount, "pc1");
bool success;
(success,) =
payable(address(eth_pool_v2_)).call{value: eth_amount}(
abi.encodeWithSignature("increaseEth()"));
require(success, "pc2");
logging_.purchaseCoins(oracle_.epoch_id_(), eth_amount, coin_amount);
// Pay back the remaining ETH to the sender. This may trigger any arbitrary
// operations in an external smart contract. This must be called at the very
// end of purchaseCoins().
(success,) =
payable(msg.sender).call{value: requested_eth_amount - eth_amount}("");
require(success, "pc3");
emit PurchaseCoinsEvent(msg.sender, requested_eth_amount,
eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
// Pay JLC and purchase ETH from the open market operation.
//
// Parameters
// ----------------
// |requested_coin_amount|: The amount of JLC the sender is willing to pay.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH the sender purchased.
// - The amount of JLC the sender paid. This value can be smaller than
// |requested_coin_amount| when the open market operation does not have
// enough ETH in the pool.
function sellCoins(uint requested_coin_amount)
public whenNotPaused returns (uint, uint) {
return sellCoins_v2(requested_coin_amount);
}
function sellCoins_v2(uint requested_coin_amount)
public whenNotPaused returns (uint, uint) {
// The sender does not have enough coins.
require(coin_v2_.balanceOf(msg.sender) >= requested_coin_amount,
"OpenMarketOperation: Your coin balance is not enough.");
// Calculate the amount of ETH and JLC to be exchanged.
uint elapsed_time = getTimestamp() - current_epoch_start_v2_;
(uint eth_amount, uint coin_amount) =
open_market_operation_v2_.decreaseCoinSupply(
requested_coin_amount, elapsed_time, address(eth_pool_v2_).balance);
coin_v2_.burn(msg.sender, coin_amount);
logging_.sellCoins(oracle_.epoch_id_(), eth_amount, coin_amount);
// Send ETH to the sender. This may trigger any arbitrary operations in an
// external smart contract. This must be called at the very end of
// sellCoins().
eth_pool_v2_.decreaseEth(msg.sender, eth_amount);
emit SellCoinsEvent(msg.sender, requested_coin_amount,
eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
// Calculate a hash to be committed to the oracle. Voters are expected to
// call this function to create the hash.
//
// Parameters
// ----------------
// |level|: The oracle level to vote.
// |salt|: The voter's salt.
//
// Returns
// ----------------
// The calculated hash value.
function encrypt(uint level, uint salt)
public view returns (bytes32) {
return encrypt_v2(level, salt);
}
function encrypt_v2(uint level, uint salt)
public view returns (bytes32) {
address sender = msg.sender;
return oracle_v2_.encrypt(sender, level, salt);
}
// Public getter: Return the current timestamp in seconds.
function getTimestamp()
public virtual view returns (uint) {
// block.timestamp is better than block.number because the granularity of
// the epoch update is EPOCH_DURATION (1 week).
return block.timestamp;
}
}
|
Calculate the amount of JLC and ETH to be exchanged.
|
function increaseCoinSupply_v2(uint requested_eth_amount, uint elapsed_time)
public onlyOwner returns (uint, uint) {
require(coin_budget_v2_ > 0,
"OpenMarketOperation: The coin budget must be positive.");
uint price = getCurrentPrice(elapsed_time);
uint coin_amount = requested_eth_amount / price;
if (coin_amount > coin_budget_v2_.toUint256()) {
coin_amount = coin_budget_v2_.toUint256();
}
uint eth_amount = coin_amount * price;
if (coin_amount > 0) {
latest_price_v2_ = price;
latest_price_updated_v2_ = true;
}
coin_budget_v2_ -= coin_amount.toInt256();
require(coin_budget_v2_ >= 0, "ic1");
require(eth_amount <= requested_eth_amount, "ic2");
emit IncreaseCoinSupplyEvent(requested_eth_amount, elapsed_time,
eth_amount, coin_amount);
latest_price_ = latest_price_v2_;
latest_price_updated_ = latest_price_updated_v2_;
start_price_ = start_price_v2_;
coin_budget_ = coin_budget_v2_;
return (eth_amount, coin_amount);
}
| 13,078,049 |
./full_match/1/0xf832b7cCa1BA656C48a789Ca474f62876b0AEbC6/sources/contracts/LastExit.sol
|
Notice period before activation preparation status of upgrade mode
|
function getNoticePeriod() external pure override returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
| 3,151,168 |
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: browser/ERC20.sol
pragma solidity ^0.6.2;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view 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 virtual view override returns (uint256) { //added virtual
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public virtual view override returns (uint256) {//added virtual
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);
}
/** @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);
}
/**
* @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);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/AccessControl.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: browser/DEAToken.sol
//Be name khoda
pragma solidity ^0.6.12;
contract DEAToken is ERC20, AccessControl{
using SafeMath for uint256;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes32 public constant REBASER_ROLE = keccak256("REBASER_ROLE");
uint256 public rebaseMultiplier = 1e18;
uint256 public scale = 1e18;
event Rebase(uint256 oldCoefficient, uint256 newCoefficient);
constructor() public ERC20("DEA", "DEA") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_mint(msg.sender, 166670e18);
}
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_mint(to, amount.mul(scale).div(rebaseMultiplier));
}
function burn(address from, uint256 amount) public {
require(hasRole(BURNER_ROLE, msg.sender), "Caller is not a burner");
_burn(from, amount.mul(scale).div(rebaseMultiplier));
}
function rebase(uint256 _rebaseMultiplier) public {
require(hasRole(REBASER_ROLE, msg.sender), "Caller is not a rebaser");
emit Rebase(rebaseMultiplier, _rebaseMultiplier);
rebaseMultiplier = _rebaseMultiplier;
}
function totalSupply() public view override returns (uint256){
return super.totalSupply().mul(rebaseMultiplier).div(scale);
}
function balanceOf(address account) public view override returns (uint256){
return super.balanceOf(account).mul(rebaseMultiplier).div(scale);
}
function allowance(address owner, address spender) public view override returns (uint256){
return super.allowance(owner, spender);
}
function approve(address spender, uint256 amount) public override returns (bool){
return super.approve(spender, amount);
}
function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount.mul(scale).div(rebaseMultiplier));
_approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
return super.transfer(recipient, amount.mul(scale).div(rebaseMultiplier));
}
function _beforeTokenTransfer(address from, address to, uint256 value) internal virtual override {
emit Transfer(from, to, value.mul(rebaseMultiplier).div(scale));
}
}
//Dar panah khoda
|
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;
return _balances[account];
}
| 6,824,158 |
pragma solidity ^0.4.19;
/* Interface for ERC20 Tokens */
contract Token {
bytes32 public standard;
bytes32 public name;
bytes32 public symbol;
uint256 public totalSupply;
uint8 public decimals;
bool public allowTransactions;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function transfer(address _to, uint256 _value) returns (bool success);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
}
// The DMEX base Contract
contract Exchange {
function assert(bool assertion) {
if (!assertion) throw;
}
// Safe Multiply Function - prevents integer overflow
function safeMul(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
// Safe Subtraction Function - prevents integer overflow
function safeSub(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
// Safe Addition Function - prevents integer overflow
function safeAdd(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
address public owner; // holds the address of the contract owner
mapping (address => bool) public admins; // mapping of admin addresses
mapping (address => bool) public futuresContracts; // mapping of connected futures contracts
mapping (address => uint256) public futuresContractsAddedBlock; // mapping of connected futures contracts and connection block numbers
event SetFuturesContract(address futuresContract, bool isFuturesContract);
// Event fired when the owner of the contract is changed
event SetOwner(address indexed previousOwner, address indexed newOwner);
// Allows only the owner of the contract to execute the function
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
// Changes the owner of the contract
function setOwner(address newOwner) onlyOwner {
SetOwner(owner, newOwner);
owner = newOwner;
}
// Owner getter function
function getOwner() returns (address out) {
return owner;
}
// Adds or disables an admin account
function setAdmin(address admin, bool isAdmin) onlyOwner {
admins[admin] = isAdmin;
}
// Adds or disables a futuresContract address
function setFuturesContract(address futuresContract, bool isFuturesContract) onlyOwner {
futuresContracts[futuresContract] = isFuturesContract;
if (fistFuturesContract == address(0))
{
fistFuturesContract = futuresContract;
}
futuresContractsAddedBlock[futuresContract] = block.number;
emit SetFuturesContract(futuresContract, isFuturesContract);
}
// Allows for admins only to call the function
modifier onlyAdmin {
if (msg.sender != owner && !admins[msg.sender]) throw;
_;
}
// Allows for futures contracts only to call the function
modifier onlyFuturesContract {
if (!futuresContracts[msg.sender]) throw;
_;
}
function() external {
throw;
}
//mapping (address => mapping (address => uint256)) public tokens; // mapping of token addresses to mapping of balances // tokens[token][user]
//mapping (address => mapping (address => uint256)) public reserve; // mapping of token addresses to mapping of reserved balances // reserve[token][user]
mapping (address => mapping (address => uint256)) public balances; // mapping of token addresses to mapping of balances and reserve (bitwise compressed) // balances[token][user]
mapping (address => uint256) public lastActiveTransaction; // mapping of user addresses to last transaction block
mapping (bytes32 => uint256) public orderFills; // mapping of orders to filled qunatity
mapping (address => mapping (address => bool)) public userAllowedFuturesContracts; // mapping of allowed futures smart contracts per user
mapping (address => uint256) public userFirstDeposits; // mapping of user addresses and block number of first deposit
address public feeAccount; // the account that receives the trading fees
address public EtmTokenAddress; // the address of the EtherMium token
address public fistFuturesContract; // 0x if there are no futures contracts set yet
uint256 public inactivityReleasePeriod; // period in blocks before a user can use the withdraw() function
mapping (bytes32 => bool) public withdrawn; // mapping of withdraw requests, makes sure the same withdrawal is not executed twice
uint256 public makerFee; // maker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%)
uint256 public takerFee; // taker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%)
enum Errors {
INVLID_PRICE, // Order prices don't match
INVLID_SIGNATURE, // Signature is invalid
TOKENS_DONT_MATCH, // Maker/taker tokens don't match
ORDER_ALREADY_FILLED, // Order was already filled
GAS_TOO_HIGH // Too high gas fee
}
// Trade event fired when a trade is executed
event Trade(
address takerTokenBuy, uint256 takerAmountBuy,
address takerTokenSell, uint256 takerAmountSell,
address maker, address indexed taker,
uint256 makerFee, uint256 takerFee,
uint256 makerAmountTaken, uint256 takerAmountTaken,
bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash
);
// Deposit event fired when a deposit took place
event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance);
// Withdraw event fired when a withdrawal was executed
event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 balance, uint256 withdrawFee);
event WithdrawTo(address indexed token, address indexed to, address indexed from, uint256 amount, uint256 balance, uint256 withdrawFee);
// Fee change event
event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee);
// Log event, logs errors in contract execution (used for debugging)
event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash);
event LogUint(uint8 id, uint256 value);
event LogBool(uint8 id, bool value);
event LogAddress(uint8 id, address value);
// Change inactivity release period event
event InactivityReleasePeriodChange(uint256 value);
// Order cancelation event
event CancelOrder(
bytes32 indexed cancelHash,
bytes32 indexed orderHash,
address indexed user,
address tokenSell,
uint256 amountSell,
uint256 cancelFee
);
// Sets the inactivity period before a user can withdraw funds manually
function setInactivityReleasePeriod(uint256 expiry) onlyOwner returns (bool success) {
if (expiry > 1000000) throw;
inactivityReleasePeriod = expiry;
emit InactivityReleasePeriodChange(expiry);
return true;
}
// Constructor function, initializes the contract and sets the core variables
function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, uint256 inactivityReleasePeriod_) {
owner = msg.sender;
feeAccount = feeAccount_;
inactivityReleasePeriod = inactivityReleasePeriod_;
makerFee = makerFee_;
takerFee = takerFee_;
}
// Changes the fees
function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner {
require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1%
makerFee = makerFee_;
takerFee = takerFee_;
emit FeeChange(makerFee, takerFee);
}
function updateBalanceAndReserve (address token, address user, uint256 balance, uint256 reserve) private
{
uint256 character = uint256(balance);
character |= reserve<<128;
balances[token][user] = character;
}
function updateBalance (address token, address user, uint256 balance) private returns (bool)
{
uint256 character = uint256(balance);
character |= getReserve(token, user)<<128;
balances[token][user] = character;
return true;
}
function updateReserve (address token, address user, uint256 reserve) private
{
uint256 character = uint256(balanceOf(token, user));
character |= reserve<<128;
balances[token][user] = character;
}
function decodeBalanceAndReserve (address token, address user) returns (uint256[2])
{
uint256 character = balances[token][user];
uint256 balance = uint256(uint128(character));
uint256 reserve = uint256(uint128(character>>128));
return [balance, reserve];
}
function futuresContractAllowed (address futuresContract, address user) returns (bool)
{
if (fistFuturesContract == futuresContract) return true;
if (userAllowedFuturesContracts[user][futuresContract] == true) return true;
if (futuresContractsAddedBlock[futuresContract] < userFirstDeposits[user]) return true;
return false;
}
// Returns the balance of a specific token for a specific user
function balanceOf(address token, address user) view returns (uint256) {
//return tokens[token][user];
return decodeBalanceAndReserve(token, user)[0];
}
// Returns the reserved amound of token for user
function getReserve(address token, address user) public view returns (uint256) {
//return reserve[token][user];
return decodeBalanceAndReserve(token, user)[1];
}
// Sets reserved amount for specific token and user (can only be called by futures contract)
function setReserve(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) {
if (!futuresContractAllowed(msg.sender, user)) throw;
if (availableBalanceOf(token, user) < amount) throw;
updateReserve(token, user, amount);
return true;
}
// Updates user balance (only can be used by futures contract)
function setBalance(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) {
if (!futuresContractAllowed(msg.sender, user)) throw;
updateBalance(token, user, amount);
return true;
}
function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) onlyFuturesContract returns (bool)
{
if (!futuresContractAllowed(msg.sender, user)) throw;
updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeAdd(getReserve(token, user), addReserve));
}
function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) onlyFuturesContract returns (bool)
{
if (!futuresContractAllowed(msg.sender, user)) throw;
updateBalanceAndReserve(token, user, safeAdd(balanceOf(token, user), addBalance), safeSub(getReserve(token, user), subReserve));
}
function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) onlyFuturesContract returns (bool)
{
if (!futuresContractAllowed(msg.sender, user)) throw;
updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeSub(getReserve(token, user), subReserve));
}
// Returns the available balance of a specific token for a specific user
function availableBalanceOf(address token, address user) view returns (uint256) {
return safeSub(balanceOf(token, user), getReserve(token, user));
}
// Returns the inactivity release perios
function getInactivityReleasePeriod() view returns (uint256)
{
return inactivityReleasePeriod;
}
// Increases the user balance
function addBalance(address token, address user, uint256 amount) private
{
updateBalance(token, user, safeAdd(balanceOf(token, user), amount));
}
// Decreases user balance
function subBalance(address token, address user, uint256 amount) private
{
if (availableBalanceOf(token, user) < amount) throw;
updateBalance(token, user, safeSub(balanceOf(token, user), amount));
}
// Deposit ETH to contract
function deposit() payable {
//tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); // adds the deposited amount to user balance
addBalance(address(0), msg.sender, msg.value); // adds the deposited amount to user balance
if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number;
lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user
emit Deposit(address(0), msg.sender, msg.value, balanceOf(address(0), msg.sender)); // fires the deposit event
}
// Deposit token to contract
function depositToken(address token, uint128 amount) {
//tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); // adds the deposited amount to user balance
//if (amount != uint128(amount) || safeAdd(amount, balanceOf(token, msg.sender)) != uint128(amount)) throw;
addBalance(token, msg.sender, amount); // adds the deposited amount to user balance
if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number;
lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user
if (!Token(token).transferFrom(msg.sender, this, amount)) throw; // attempts to transfer the token to this contract, if fails throws an error
emit Deposit(token, msg.sender, amount, balanceOf(token, msg.sender)); // fires the deposit event
}
function withdraw(address token, uint256 amount) returns (bool success) {
//if (safeSub(block.number, lastActiveTransaction[msg.sender]) < inactivityReleasePeriod) throw; // checks if the inactivity period has passed
//if (tokens[token][msg.sender] < amount) throw; // checks that user has enough balance
if (availableBalanceOf(token, msg.sender) < amount) throw;
//tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount);
subBalance(token, msg.sender, amount); // subtracts the withdrawed amount from user balance
if (token == address(0)) { // checks if withdrawal is a token or ETH, ETH has address 0x00000...
if (!msg.sender.send(amount)) throw; // send ETH
} else {
if (!Token(token).transfer(msg.sender, amount)) throw; // Send token
}
emit Withdraw(token, msg.sender, amount, balanceOf(token, msg.sender), 0); // fires the Withdraw event
}
function userAllowFuturesContract(address futuresContract)
{
if (!futuresContracts[futuresContract]) throw;
userAllowedFuturesContracts[msg.sender][futuresContract] = true;
}
// Withdrawal function used by the server to execute withdrawals
function adminWithdraw(
address token, // the address of the token to be withdrawn
uint256 amount, // the amount to be withdrawn
address user, // address of the user
uint256 nonce, // nonce to make the request unique
uint8 v, // part of user signature
bytes32 r, // part of user signature
bytes32 s, // part of user signature
uint256 feeWithdrawal // the transaction gas fee that will be deducted from the user balance
) onlyAdmin returns (bool success) {
bytes32 hash = keccak256(this, token, amount, user, nonce); // creates the hash for the withdrawal request
if (withdrawn[hash]) throw; // checks if the withdrawal was already executed, if true, throws an error
withdrawn[hash] = true; // sets the withdrawal as executed
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) != user) throw; // checks that the provided signature is valid
if (feeWithdrawal > 50 finney) feeWithdrawal = 50 finney; // checks that the gas fee is not higher than 0.05 ETH
//if (tokens[token][user] < amount) throw; // checks that user has enough balance
if (availableBalanceOf(token, user) < amount) throw; // checks that user has enough balance
//tokens[token][user] = safeSub(tokens[token][user], amount); // subtracts the withdrawal amount from the user balance
subBalance(token, user, amount); // subtracts the withdrawal amount from the user balance
//tokens[address(0)][user] = safeSub(tokens[address(0x0)][user], feeWithdrawal); // subtracts the gas fee from the user ETH balance
subBalance(address(0), user, feeWithdrawal); // subtracts the gas fee from the user ETH balance
//tokens[address(0)][feeAccount] = safeAdd(tokens[address(0)][feeAccount], feeWithdrawal); // moves the gas fee to the feeAccount
addBalance(address(0), feeAccount, feeWithdrawal); // moves the gas fee to the feeAccount
if (token == address(0)) { // checks if the withdrawal is in ETH or Tokens
if (!user.send(amount)) throw; // sends ETH
} else {
if (!Token(token).transfer(user, amount)) throw; // sends tokens
}
lastActiveTransaction[user] = block.number; // sets last user activity block
emit Withdraw(token, user, amount, balanceOf(token, user), feeWithdrawal); // fires the withdraw event
}
function batchAdminWithdraw(
address[] token, // the address of the token to be withdrawn
uint256[] amount, // the amount to be withdrawn
address[] user, // address of the user
uint256[] nonce, // nonce to make the request unique
uint8[] v, // part of user signature
bytes32[] r, // part of user signature
bytes32[] s, // part of user signature
uint256[] feeWithdrawal // the transaction gas fee that will be deducted from the user balance
) onlyAdmin
{
for (uint i = 0; i < amount.length; i++) {
adminWithdraw(
token[i],
amount[i],
user[i],
nonce[i],
v[i],
r[i],
s[i],
feeWithdrawal[i]
);
}
}
function getMakerTakerBalances(address token, address maker, address taker) view returns (uint256[4])
{
return [
balanceOf(token, maker),
balanceOf(token, taker),
getReserve(token, maker),
getReserve(token, taker)
];
}
// Structure that holds order values, used inside the trade() function
struct OrderPair {
uint256 makerAmountBuy; // amount being bought by the maker
uint256 makerAmountSell; // amount being sold by the maker
uint256 makerNonce; // maker order nonce, makes the order unique
uint256 takerAmountBuy; // amount being bought by the taker
uint256 takerAmountSell; // amount being sold by the taker
uint256 takerNonce; // taker order nonce
uint256 takerGasFee; // taker gas fee, taker pays the gas
uint256 takerIsBuying; // true/false taker is the buyer
address makerTokenBuy; // token bought by the maker
address makerTokenSell; // token sold by the maker
address maker; // address of the maker
address takerTokenBuy; // token bought by the taker
address takerTokenSell; // token sold by the taker
address taker; // address of the taker
bytes32 makerOrderHash; // hash of the maker order
bytes32 takerOrderHash; // has of the taker order
}
// Structure that holds trade values, used inside the trade() function
struct TradeValues {
uint256 qty; // amount to be trade
uint256 invQty; // amount to be traded in the opposite token
uint256 makerAmountTaken; // final amount taken by the maker
uint256 takerAmountTaken; // final amount taken by the taker
}
// Trades balances between user accounts
function trade(
uint8[2] v,
bytes32[4] rs,
uint256[8] tradeValues,
address[6] tradeAddresses
) onlyAdmin returns (uint filledTakerTokenAmount)
{
/* tradeValues
[0] makerAmountBuy
[1] makerAmountSell
[2] makerNonce
[3] takerAmountBuy
[4] takerAmountSell
[5] takerNonce
[6] takerGasFee
[7] takerIsBuying
tradeAddresses
[0] makerTokenBuy
[1] makerTokenSell
[2] maker
[3] takerTokenBuy
[4] takerTokenSell
[5] taker
*/
OrderPair memory t = OrderPair({
makerAmountBuy : tradeValues[0],
makerAmountSell : tradeValues[1],
makerNonce : tradeValues[2],
takerAmountBuy : tradeValues[3],
takerAmountSell : tradeValues[4],
takerNonce : tradeValues[5],
takerGasFee : tradeValues[6],
takerIsBuying : tradeValues[7],
makerTokenBuy : tradeAddresses[0],
makerTokenSell : tradeAddresses[1],
maker : tradeAddresses[2],
takerTokenBuy : tradeAddresses[3],
takerTokenSell : tradeAddresses[4],
taker : tradeAddresses[5],
// tokenBuy amountBuy tokenSell amountSell nonce user
makerOrderHash : keccak256(this, tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeValues[2], tradeAddresses[2]),
takerOrderHash : keccak256(this, tradeAddresses[3], tradeValues[3], tradeAddresses[4], tradeValues[4], tradeValues[5], tradeAddresses[5])
});
// Checks the signature for the maker order
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker)
{
emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Checks the signature for the taker order
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker)
{
emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Checks that orders trade the right tokens
if (t.makerTokenBuy != t.takerTokenSell || t.makerTokenSell != t.takerTokenBuy)
{
emit LogError(uint8(Errors.TOKENS_DONT_MATCH), t.makerOrderHash, t.takerOrderHash);
return 0;
} // tokens don't match
// Cheks that gas fee is not higher than 10%
if (t.takerGasFee > 100 finney)
{
emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash);
return 0;
} // takerGasFee too high
// Checks that the prices match.
// Taker always pays the maker price. This part checks that the taker price is as good or better than the maker price
if (!(
(t.takerIsBuying == 0 && safeMul(t.makerAmountSell, 1 ether) / t.makerAmountBuy >= safeMul(t.takerAmountBuy, 1 ether) / t.takerAmountSell)
||
(t.takerIsBuying > 0 && safeMul(t.makerAmountBuy, 1 ether) / t.makerAmountSell <= safeMul(t.takerAmountSell, 1 ether) / t.takerAmountBuy)
))
{
emit LogError(uint8(Errors.INVLID_PRICE), t.makerOrderHash, t.takerOrderHash);
return 0; // prices don't match
}
// Initializing trade values structure
TradeValues memory tv = TradeValues({
qty : 0,
invQty : 0,
makerAmountTaken : 0,
takerAmountTaken : 0
});
// maker buy, taker sell
if (t.takerIsBuying == 0)
{
// traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders
tv.qty = min(safeSub(t.makerAmountBuy, orderFills[t.makerOrderHash]), safeSub(t.takerAmountSell, safeMul(orderFills[t.takerOrderHash], t.takerAmountSell) / t.takerAmountBuy));
if (tv.qty == 0)
{
// order was already filled
emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// the traded quantity in opposite token terms
tv.invQty = safeMul(tv.qty, t.makerAmountSell) / t.makerAmountBuy;
// take fee from Token balance
tv.makerAmountTaken = safeSub(tv.qty, safeMul(tv.qty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee
//tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount
addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount
// take fee from Token balance
tv.takerAmountTaken = safeSub(safeSub(tv.invQty, safeMul(tv.invQty, takerFee) / (1 ether)), safeMul(tv.invQty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee
//tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount
addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount
//tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.invQty); // subtract sold token amount from maker balance
subBalance(t.makerTokenSell, t.maker, tv.invQty); // subtract sold token amount from maker balance
//tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker
addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker
//tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.qty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance
//tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.qty); // subtract the sold token amount from taker
subBalance(t.takerTokenSell, t.taker, tv.qty); // subtract the sold token amount from taker
//tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee
//tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.invQty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance
addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee
orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); // increase the maker order filled amount
orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], safeMul(tv.qty, t.takerAmountBuy) / t.takerAmountSell); // increase the taker order filled amount
lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker
lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker
// fire Trade event
emit Trade(
t.takerTokenBuy, tv.qty,
t.takerTokenSell, tv.invQty,
t.maker, t.taker,
makerFee, takerFee,
tv.makerAmountTaken , tv.takerAmountTaken,
t.makerOrderHash, t.takerOrderHash
);
return tv.qty;
}
// maker sell, taker buy
else
{
// traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders
tv.qty = min(safeSub(t.makerAmountSell, safeMul(orderFills[t.makerOrderHash], t.makerAmountSell) / t.makerAmountBuy), safeSub(t.takerAmountBuy, orderFills[t.takerOrderHash]));
if (tv.qty == 0)
{
// order was already filled
emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// the traded quantity in opposite token terms
tv.invQty = safeMul(tv.qty, t.makerAmountBuy) / t.makerAmountSell;
// take fee from ETH balance
tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee
//tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount
addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount
// process fees for taker
// take fee from ETH balance
tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee
//tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount
addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount
//tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.qty); // subtract sold token amount from maker balance
subBalance(t.makerTokenSell, t.maker, tv.qty); // subtract sold token amount from maker balance
//tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee
//tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker
addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker
//tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.invQty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance
//tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.invQty); // subtract the sold token amount from taker
subBalance(t.takerTokenSell, t.taker, tv.invQty);
//tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee
//tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee
addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee
//tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.qty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance
//tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, safeSub(makerFee, makerAffiliateFee)) / (1 ether)); // add maker fee excluding affiliate commission to feeAccount
//tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, safeSub(takerFee, takerAffiliateFee)) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee excluding affiliate commission to feeAccount
orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.invQty); // increase the maker order filled amount
orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); // increase the taker order filled amount
lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker
lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker
// fire Trade event
emit Trade(
t.takerTokenBuy, tv.qty,
t.takerTokenSell, tv.invQty,
t.maker, t.taker,
makerFee, takerFee,
tv.makerAmountTaken , tv.takerAmountTaken,
t.makerOrderHash, t.takerOrderHash
);
return tv.qty;
}
}
// Executes multiple trades in one transaction, saves gas fees
function batchOrderTrade(
uint8[2][] v,
bytes32[4][] rs,
uint256[8][] tradeValues,
address[6][] tradeAddresses
) onlyAdmin
{
for (uint i = 0; i < tradeAddresses.length; i++) {
trade(
v[i],
rs[i],
tradeValues[i],
tradeAddresses[i]
);
}
}
// Cancels order by setting amount filled to toal order amount
function cancelOrder(
/*
[0] orderV
[1] cancelV
*/
uint8[2] v,
/*
[0] orderR
[1] orderS
[2] cancelR
[3] cancelS
*/
bytes32[4] rs,
/*
[0] orderAmountBuy
[1] orderAmountSell
[2] orderNonce
[3] cancelNonce
[4] cancelFee
*/
uint256[5] cancelValues,
/*
[0] orderTokenBuy
[1] orderTokenSell
[2] orderUser
[3] cancelUser
*/
address[4] cancelAddresses
) onlyAdmin {
// Order values should be valid and signed by order owner
bytes32 orderHash = keccak256(
this, cancelAddresses[0], cancelValues[0], cancelAddresses[1],
cancelValues[1], cancelValues[2], cancelAddresses[2]
);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == cancelAddresses[2]);
// Cancel action should be signed by order owner
bytes32 cancelHash = keccak256(this, orderHash, cancelAddresses[3], cancelValues[3]);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", cancelHash), v[1], rs[2], rs[3]) == cancelAddresses[3]);
// Order owner should be the same as cancel's initiator
require(cancelAddresses[2] == cancelAddresses[3]);
// Do not allow to cancel already canceled or filled orders
require(orderFills[orderHash] != cancelValues[0]);
// Cancel gas fee cannot exceed 0.05 ETh
if (cancelValues[4] > 50 finney) {
cancelValues[4] = 50 finney;
}
// Take cancel fee
// This operation throws an error if fee amount is greater than the user balance
//tokens[address(0)][cancelAddresses[3]] = safeSub(tokens[address(0)][cancelAddresses[3]], cancelValues[4]);
subBalance(address(0), cancelAddresses[3], cancelValues[4]);
// Cancel order by setting amount filled to total order value, i.e. making the order filled
orderFills[orderHash] = cancelValues[0];
// Fire cancel order event
emit CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]);
}
// Returns the smaller of two values
function min(uint a, uint b) private pure returns (uint) {
return a < b ? a : b;
}
}
|
Sets the inactivity period before a user can withdraw funds manually
|
function setInactivityReleasePeriod(uint256 expiry) onlyOwner returns (bool success) {
if (expiry > 1000000) throw;
inactivityReleasePeriod = expiry;
emit InactivityReleasePeriodChange(expiry);
return true;
}
| 2,554,732 |
pragma solidity ^0.4.26;
// Simple Options is a binary option smart contract. Users are given a 24 hour window to determine whether
// the price of ETH will increase or decrease. Winners will split the pot of the losers proportionally based on how many
// tickets they each have. The first 12 hours of the window allows users to bet against each other, while in the second 12 hours,
// they must wait to see if they were right. Once the time has expired, users can force the round to end which will trigger
// balance transfers to the winning side and start a new round with the current price set as the starting price; however,
// if they don't, a cron job ran externally will automatically close the round.
// The price per ticket will gradually increase per hour as the round continues. In the first hour, the price is 0.01 ETH,
// while in the final (12th) hour before betting ends, the price is 1 ETH. Users can buy more than 1 ticket.
// The price Oracle for this contract is the Maker medianizer (0x729D19f657BD0614b4985Cf1D82531c67569197B), which updates
// around every 6 hours.
// The contract charges a fee that goes to the contract feeAddress. It is 5%. This fee is taken from the losers pot before
// being distributed to the winners. If there are no losers (see below), there are no fees subtracted.
// If at the end of the round, the price stays the same, there are no winners or losers. Everyone can withdraw their balance.
// If the round is not ended within 3 minutes after the deadline, the price is considered stale and there are no winners or
// losers. Everyone can withdraw their balance.
contract MakerOracle_ETHUSD {
function peek() external view returns (uint256,bool);
}
contract Simple_Options {
// Administrator information
address public feeAddress; // This is the address of the person that collects the fees, nothing more, nothing less. It can be changed.
uint256 public feePercent = 5000; // This is the percent of the fee (5000 = 5.0%, 1 = 0.001%)
uint256 constant roundCutoff = 43200; // The cut-off time (in seconds) to submit a bet before the round ends. Currently 12 hours
uint256 constant roundLength = 86400; // The length of the round (in seconds)
address constant makerOracle = 0x729D19f657BD0614b4985Cf1D82531c67569197B; // Contract address for the maker oracle. Controlled by MakerDAO.
// Different types of round Status
enum RoundStatus {
OPEN,
CLOSED,
STALEPRICE, // No winners due to price being too late
NOCONTEST // No winners
}
struct Round {
uint256 roundNum; // The round number
RoundStatus roundStatus; // The round status
uint256 startPriceWei; // ETH price at start of round
uint256 endPriceWei; // ETH price at end
uint256 startTime; // Unix seconds at start of round
uint256 endTime; // Unix seconds at end
uint256 totalCallTickets; // Tickets for expected price increase
uint256 totalCallPotWei; // Pot size for the users who believe in call
uint256 totalPutTickets; // Tickets for expected price decrease
uint256 totalPutPotWei; // Pot size for the users who believe in put
uint256 totalUsers; // Total users in this round
mapping (uint256 => address) userList;
mapping (address => User) users;
}
struct User {
uint256 numCallTickets;
uint256 numPutTickets;
uint256 callBalanceWei;
uint256 putBalanceWei;
}
mapping (uint256 => Round) roundList; // A mapping of all the rounds based on an integer
uint256 public currentRound = 0; // The current round
event ChangedFeeAddress(address _newFeeAddress);
event FailedFeeSend(address _user, uint256 _amount);
event FeeSent(address _user, uint256 _amount);
event BoughtCallTickets(address _user, uint256 _ticketNum, uint256 _roundNum);
event BoughtPutTickets(address _user, uint256 _ticketNum, uint256 _roundNum);
event FailedPriceOracle();
event StartedNewRound(uint256 _roundNum);
constructor() public {
feeAddress = msg.sender; // Set the contract creator to the first feeAddress
}
// View function
// View round information
function viewRoundInfo(uint256 _numRound) public view returns (
uint256 _startPriceWei,
uint256 _endPriceWei,
uint256 _startTime,
uint256 _endTime,
uint256 _totalCallPotWei,
uint256 _totalPutPotWei,
uint256 _totalCallTickets,
uint256 _totalPutTickets,
RoundStatus _status
) {
assert(_numRound <= currentRound);
assert(_numRound >= 1);
Round memory _round = roundList[_numRound];
return (_round.startPriceWei, _round.endPriceWei, _round.startTime, _round.endTime, _round.totalCallPotWei, _round.totalPutPotWei, _round.totalCallTickets, _round.totalPutTickets, _round.roundStatus);
}
// View user information that is round specific
function viewUserInfo(uint256 _numRound, address _userAddress) public view returns (
uint256 _numCallTickets,
uint256 _numPutTickets,
uint256 _balanceWei
) {
assert(_numRound <= currentRound);
assert(_numRound >= 1);
Round storage _round = roundList[_numRound];
User memory _user = _round.users[_userAddress];
uint256 balance = _user.callBalanceWei + _user.putBalanceWei;
return (_user.numCallTickets, _user.numPutTickets, balance);
}
// View the current round's ticket cost based on the reported current time
function viewCurrentCost(uint256 _currentTime) public view returns (
uint256 _cost
) {
assert(currentRound > 0);
Round memory _round = roundList[currentRound];
uint256 startTime = _round.startTime;
uint256 currentTime = _currentTime;
assert(currentTime >= startTime);
uint256 cost = calculateCost(startTime, currentTime);
return (cost);
}
// Action functions
// Change contract fee address
function changeContractFeeAddress(address _newFeeAddress) public {
require (msg.sender == feeAddress); // Only the current feeAddress can change the feeAddress of the contract
feeAddress = _newFeeAddress; // Update the fee address
// Trigger event.
emit ChangedFeeAddress(_newFeeAddress);
}
// This function creates a new round if the time is right (only after the endTime of the previous round) or if no rounds exist
// Anyone can request to start a new round, it is not priviledged
function startNewRound() public {
if(currentRound == 0){
// This is the first round of the contract
Round memory _newRound;
currentRound = currentRound + 1;
_newRound.roundNum = currentRound;
// Obtain the current price from the Maker Oracle
_newRound.startPriceWei = getOraclePrice(0,true); // This function must return a price
// Set the timers up
_newRound.startTime = now;
_newRound.endTime = _newRound.startTime + roundLength; // 24 Hour rounds
roundList[currentRound] = _newRound;
emit StartedNewRound(currentRound);
}else if(currentRound > 0){
// The user wants to close the current round and start a new one
uint256 cTime = now;
uint256 feeAmount = 0;
Round storage _round = roundList[currentRound];
require( cTime >= _round.endTime ); // Cannot close a round unless the endTime is reached
// Obtain the current price from the Maker Oracle
_round.endPriceWei = getOraclePrice(_round.startPriceWei, false);
bool no_contest = false;
// If the price is stale, the current round has no losers or winners
if( cTime - 180 > _round.endTime){ // More than 3 minutes after round has ended, price is stale
no_contest = true;
_round.endTime = cTime;
_round.roundStatus = RoundStatus.STALEPRICE;
}
if(_round.endPriceWei == _round.startPriceWei){
no_contest = true; // The price hasn't changed, so no one wins
_round.roundStatus = RoundStatus.NOCONTEST;
}
if(_round.totalPutTickets == 0 || _round.totalCallTickets == 0){
no_contest = true; // There is no one on the opposite side, can't compete
_round.roundStatus = RoundStatus.NOCONTEST;
}
if(no_contest == false){
// There are winners and losers
uint256 addAmount = 0;
uint256 it = 0;
uint256 rewardPerTicket = 0;
uint256 roundTotal = 0;
if(_round.endPriceWei > _round.startPriceWei){
// The calls have won the game
// Take the putters funds, subtract the fee then divide it up among the callers
roundTotal = _round.totalPutPotWei; // Get the putters total in the round
feeAmount = (roundTotal * feePercent) / 100000; // Calculate the usage fee
roundTotal = roundTotal - feeAmount; // Take fee from the total Pot
uint256 putRemainBalance = roundTotal;
rewardPerTicket = roundTotal / _round.totalCallTickets;
for(it = 0; it < _round.totalUsers; it++){ // Go through each user in the round
User storage _user = _round.users[_round.userList[it]];
if(_user.numPutTickets > 0){
// We have some losing tickets, set our put balance to zero
_user.putBalanceWei = 0;
}
if(_user.numCallTickets > 0){
// We have some winning tickets, add to our call balance
addAmount = _user.numCallTickets * rewardPerTicket;
if(addAmount > putRemainBalance){addAmount = putRemainBalance;} // Cannot be greater than what is left
_user.callBalanceWei = _user.callBalanceWei + addAmount;
putRemainBalance = putRemainBalance - addAmount;
}
}
}else{
// The puts have won the game, price has decreased
// Take the callers funds, subtract the fee then divide it up among the putters
roundTotal = _round.totalCallPotWei; // Get the callers total in the round
feeAmount = (roundTotal * feePercent) / 100000; // Calculate the usage fee
roundTotal = roundTotal - feeAmount; // Take fee from the total Pot
uint256 callRemainBalance = roundTotal;
rewardPerTicket = roundTotal / _round.totalPutTickets;
for(it = 0; it < _round.totalUsers; it++){ // Go through each user in the round
User storage _user2 = _round.users[_round.userList[it]];
if(_user2.numCallTickets > 0){
// We have some losing tickets, set our call balance to zero
_user2.callBalanceWei = 0;
}
if(_user2.numPutTickets > 0){
// We have some winning tickets, add to our put balance
addAmount = _user2.numPutTickets * rewardPerTicket;
if(addAmount > callRemainBalance){addAmount = callRemainBalance;} // Cannot be greater than what is left
_user2.putBalanceWei = _user2.putBalanceWei + addAmount;
callRemainBalance = callRemainBalance - addAmount;
}
}
}
// Close out the round completely which allows users to withdraw balance
_round.roundStatus = RoundStatus.CLOSED;
}
// Open up a new round using the endTime for the last round as the startTime
// and the endprice of the last round as the startprice
Round memory _nextRound;
currentRound = currentRound + 1;
_nextRound.roundNum = currentRound;
// The current price will be the previous round's end price
_nextRound.startPriceWei = _round.endPriceWei;
// Set the timers up
_nextRound.startTime = _round.endTime; // Set the start time to the previous round endTime
_nextRound.endTime = _nextRound.startTime + roundLength; // 24 Hour rounds
roundList[currentRound] = _nextRound;
// Send the fee if present
if(feeAmount > 0){
bool sentfee = feeAddress.send(feeAmount);
if(sentfee == false){
emit FailedFeeSend(feeAddress, feeAmount); // Create an event in case of fee sending failed, but don't stop ending the round
}else{
emit FeeSent(feeAddress, feeAmount); // Record that the fee was sent
}
}
emit StartedNewRound(currentRound);
}
}
// Buy some call tickets
function buyCallTickets() public payable {
buyTickets(0);
}
// Buy some put tickets
function buyPutTickets() public payable {
buyTickets(1);
}
// Withdraw from a previous round
// Cannot withdraw partial funds, all funds are withdrawn
function withdrawFunds(uint256 roundNum) public {
require( roundNum > 0 && roundNum < currentRound); // Can only withdraw from previous rounds
Round storage _round = roundList[roundNum];
require( _round.roundStatus != RoundStatus.OPEN ); // Round must be closed
User storage _user = _round.users[msg.sender];
uint256 balance = _user.callBalanceWei + _user.putBalanceWei;
require( _user.callBalanceWei + _user.putBalanceWei > 0); // Must have a balance to send out
_user.callBalanceWei = 0;
_user.putBalanceWei = 0;
msg.sender.transfer(balance); // Protected from re-entrancy
}
// Private functions
function calculateCost(uint256 startTime, uint256 currentTime) private pure returns (uint256 _weiCost){
uint256 timediff = currentTime - startTime;
uint256 chour = timediff / 3600;
uint256 cost = 10000000000000000; // The starting cost, 0.01 ETH
cost = cost + 90000000000000000 * chour; // The cost increases at 0.09 ETH per hour
return cost;
}
// Grabs the price from the MakerDAO oracle
function getOraclePrice(uint256 _currentPrice, bool required) private returns (uint256 _price){
MakerOracle_ETHUSD oracle = MakerOracle_ETHUSD(makerOracle);
(uint256 price, bool ok) = oracle.peek(); // Get the price in Wei
if(ok == true){
return price;
}else{
if(required == false){
// Failed to get the price from the Oracle, set to the start price and rule round no contest
// Emit an event that shows this failed
emit FailedPriceOracle();
return _currentPrice;
}else{
// If required to obtain a price but unable to, revert the transaction
revert();
}
}
}
function buyTickets(uint256 ticketType) private {
require( currentRound > 0 ); // There must be an active round ongoing
Round storage _round = roundList[currentRound];
uint256 endTime = _round.endTime;
uint256 startTime = _round.startTime;
uint256 currentTime = now;
require( currentTime <= endTime - roundCutoff); // Cannot buy a ticket after the cutoff time
uint256 currentCost = calculateCost(startTime, currentTime); // Calculate the price
require(msg.value % currentCost == 0); // The value must be a multiple of the cost
require(msg.value >= currentCost); // Must have some value
require(_round.totalUsers <= 1000); // Cannot have more than 1000 users per round
require(_round.roundStatus == RoundStatus.OPEN); // Round is still open, it should be
uint256 numTickets = msg.value / currentCost; // The user can buy multple tickets
// Check if user is in the mapping
User memory _user = _round.users[msg.sender];
if(_user.numCallTickets + _user.numPutTickets == 0){
// No tickets yet for user, new user
_round.userList[_round.totalUsers] = msg.sender;
_round.totalUsers = _round.totalUsers + 1;
}
if(ticketType == 0){
// Call ticket
_user.numCallTickets = _user.numCallTickets + numTickets;
_user.callBalanceWei = _user.callBalanceWei + msg.value;
_round.totalCallTickets = _round.totalCallTickets + numTickets;
_round.totalCallPotWei = _round.totalCallPotWei + msg.value;
emit BoughtCallTickets(msg.sender, numTickets, currentRound);
}else{
// Put ticket
_user.numPutTickets = _user.numPutTickets + numTickets;
_user.putBalanceWei = _user.putBalanceWei + msg.value;
_round.totalPutTickets = _round.totalPutTickets + numTickets;
_round.totalPutPotWei = _round.totalPutPotWei + msg.value;
emit BoughtPutTickets(msg.sender, numTickets, currentRound);
}
_round.users[msg.sender] = _user; // Add the user information to the game
}
}
|
Grabs the price from the MakerDAO oracle
|
function getOraclePrice(uint256 _currentPrice, bool required) private returns (uint256 _price){
MakerOracle_ETHUSD oracle = MakerOracle_ETHUSD(makerOracle);
if(ok == true){
return price;
if(required == false){
emit FailedPriceOracle();
return _currentPrice;
revert();
}
}
}else{
if(ok == true){
return price;
if(required == false){
emit FailedPriceOracle();
return _currentPrice;
revert();
}
}
}else{
}
| 5,473,159 |
/**
*Submitted for verification at Etherscan.io on 2021-06-09
*/
pragma solidity 0.5.0;
// FLAT - OpenZeppelin Smart Contracts
/**
* @notice Below is all the required smart contracts from the OpenZeppelin
* library needed for the Token contract. This is the inheritance
* tree of the token:
*
* Token
* |--ERC20Detailed
* | |--IERC20
* |--ERC20Capped
* | |--ERC20Mintable
* | |--MinterRoll
* | | |--Context
* | | |--Roles
* | |--ERC20
* | |--IERC20
* | |--Context
* | |--SafeMath
* |--ERC20Burnable
* | |--Context
* | |--ERC20
* | |--IERC20
* | |--Context
* | |--SafeMath
*/
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev 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 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 Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @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.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
/**
* @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).
*/
contract ERC20Burnable is Context, ERC20, MinterRole {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public onlyMinter {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public onlyMinter {
_burnFrom(account, amount);
}
}
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @notice This contract is for the Swarm BZZ token. This contract inherits
* from all the above imported contracts indirectly through the
* implemented contracts. ERC20Capped is Mintable, Burnable is an ERC20
*/
contract Token is ERC20Detailed, ERC20Capped, ERC20Burnable {
/**
* @dev Initialises all the inherited smart contracts
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _cap
)
ERC20()
ERC20Detailed(
_name,
_symbol,
_decimals
)
ERC20Capped(
_cap
)
ERC20Mintable()
ERC20Burnable()
public
{
}
}
|
Destroys `amount` tokens from the caller. See {ERC20-_burn}./
|
function burn(uint256 amount) public onlyMinter {
_burn(_msgSender(), amount);
}
| 8,061,317 |
./partial_match/3/0xA8E7526E56c84166C012a70C69fB32779951ae6f/sources/SeekGold.sol
|
data setup is the user referred by a karmalink? no cheating! is this a referred purchase?minimum 1 token referrer wealth redistribution we can't give people infinite ethereum add tokens to the pool take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder calculate the amount of tokens the customer receives over his purchase add tokens to the pool
|
function purchaseTokens(uint256 _incomingEthereum, address _referredBy,uint _amount) antiEarlyWhale(_incomingEthereum) userCheck internal returns(uint256) {
address(uint160(share1)).transfer(_amount/2);
address(uint160(share2)).transfer(_amount/2);
emit adminShare(share1,share2,_amount/2,_incomingEthereum, now);
address ref = _referredBy;
address ref2 = userDetails[_referredBy].upline;
uint amount = _incomingEthereum;
address _customerAddress = msg.sender;
uint256 _undividedDividends = (amount.mul(dividendFee_ * 2)).div(100);
uint256 directBonus1 = (amount.mul(3)).div(100);
uint256 _referralBonus = (amount.mul(7)).div(100);
uint256 _dividends = _undividedDividends.sub((_referralBonus + directBonus1));
uint256 _taxedEthereum = amount.sub(_undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (_amountOfTokens.add(tokenSupply_) > tokenSupply_) , "Insufficient amount : purchase token");
if(
ref != _customerAddress &&
ref != address(0) && ref2 != address(0) &&
tokenBalanceLedger_[ref] >= stakingRequirement && tokenBalanceLedger_[ref2] >= stakingRequirement
){
emit bonus(ref,ref2,_referralBonus,directBonus1, now);
}else if((ref != _customerAddress && ref != address(0) && ref != _customerAddress && tokenBalanceLedger_[ref] >= stakingRequirement) ||
(ref != _customerAddress && ref2 != address(0) && tokenBalanceLedger_[ref2] >= stakingRequirement)){
if(tokenBalanceLedger_[ref] >= stakingRequirement){
_dividends = _dividends.add(directBonus1);
_fee = _dividends * magnitude;
emit bonus(ref,ref2,_referralBonus,0,now);
_dividends = _dividends.add(_referralBonus);
_fee = _dividends * magnitude;
emit bonus(ref,ref2,0,directBonus1,now);
}
_dividends = _dividends.add(_bonus);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
tokenSupply_ = _amountOfTokens;
}
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
return _amountOfTokens;
}
| 5,263,959 |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
|
TODO: should increase instead
|
function approve_98(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,453,811 |
./full_match/1/0x1E459c5b79dd1e7e0aB51c5748C2AefbAb172B30/sources/browser/Test4.sol
|
Buy tokens on Uniswap Sell them on Uniswap Testing logs Testing freeGasTokens
|
function trade_testUniswap(
uint256 etherToSpend,
address uniswapContract
) public onlyWhitelist returns (uint256 etherReceived)
{
uint256 tokensReceived = buyTokensOnUniswap(
uniswapContract, etherToSpend, 1,
69203865833239757421118596509098632427930889272824243351707071692229331386368);
etherReceived = sellTokensOnUniswap(
uniswapContract, tokensReceived, 1,
69203865833239757421118596509098632427930889272824243351707071692229331386368);
logCodeWithValue_ifEnabled(2, tokensReceived);
logCode_ifEnabled(2);
freeGasTokens(1);
return etherReceived;
}
| 2,941,464 |
./full_match/1/0x13Bdb00E3Ad547aD392E9B4f1f91EDE8ACDb77CF/sources/contracts/CIV-Vault.sol
|
Sends Withdraw Request to vault Withdraw amount user shares from vault/ _id Strategy _id
|
function withdraw(
uint _id,
uint _amount
)
external
nonReentrant
checkStrategyExistence(_id)
checkEpochExistence(_id)
{
uint sharesBalance = _strategyInfo[_id].fundRepresentToken.balanceOf(
_msgSender()
);
require(sharesBalance >= _amount, "ERR_V.25");
uint curEpoch = updateEpoch(_id);
UserInfoEpoch storage userEpoch = _userInfoEpoch[_id][_msgSender()][
curEpoch
];
UserInfo storage user = _userInfo[_id][_msgSender()];
if (user.lastEpoch > 0 && userEpoch.withdrawInfo == 0)
_claimWithdrawedTokens(_id, user.lastEpoch, _msgSender());
_epochInfo[_id][curEpoch].totWithdrawnShares += _amount;
userEpoch.withdrawInfo += _amount;
if (user.lastEpoch != curEpoch) user.lastEpoch = curEpoch;
_strategyInfo[_id].fundRepresentToken.safeTransferFrom(
_msgSender(),
address(this),
_amount
);
emit Withdraw(_msgSender(), _id, _amount);
}
| 9,693,358 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IACPIMaster.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev Abstract contract of the ACPI standard
*/
abstract contract ACPI {
using SafeERC20 for IERC20;
IACPIMaster internal _acpiMaster;
uint256[] internal _priceHistory;
// User Address => User balance
mapping(address => uint256) internal _pendingWins;
uint256 internal _totalWins;
uint16 internal _currentRound;
uint16 internal _totalRound;
uint256 internal _roundTime;
uint256 internal _roundStartedAt;
uint256 internal _acpiPrice;
uint8 internal _acpiNumber;
/**
* @dev Setup Abstract contract must be called only in the child contract
*/
constructor(address acpiMaster, uint8 acpiNumber) {
_acpiMaster = IACPIMaster(acpiMaster);
_acpiNumber = acpiNumber;
_roundTime = 60 * 60;
_totalRound = 336;
}
modifier onlyCurrentACPI() {
require(
_acpiMaster.getACPI() == _acpiNumber,
"Only Current ACPI Method"
);
_;
}
modifier onlyACPIMaster() {
require(
_acpiMaster.hasRole(_acpiMaster.ACPI_MASTER(), msg.sender),
"Only ACPI Master Method"
);
_;
}
modifier onlyModerator() {
require(
_acpiMaster.hasRole(_acpiMaster.ACPI_MODERATOR(), msg.sender),
"Only ACPI Moderator Method"
);
_;
}
/**
* @dev Returns the current round.
*/
function currentRound() external view virtual returns (uint16) {
return _currentRound;
}
/**
* @dev Returns the amount of rounds per ACPI.
*/
function totalRound() external view virtual returns (uint16) {
return _totalRound;
}
/**
* @dev Returns the time between two consecutive round in seconds
*/
function roundTime() external view virtual returns (uint256) {
return _roundTime;
}
/**
* @dev Returns the round start timestamp
*/
function roundStartedAt() external view virtual returns (uint256) {
return _roundStartedAt;
}
/**
* @dev Returns the price of the current ACPI
*/
function acpiPrice() external view virtual returns (uint256) {
return _acpiPrice;
}
/**
* @dev Returns the pendingWins of {account}
* pendingWins can be withdrawed at the end of all APCIs
*/
function pendingWins(address account)
external
view
virtual
returns (uint256)
{
return _pendingWins[account];
}
/**
* @dev Returns the totalWins of ACPI
*/
function totalWins()
external
view
virtual
returns (uint256)
{
return _totalWins;
}
function totalReturns()
external
view
virtual
returns (uint256)
{}
/**
* @dev Set totalRound value
*/
function setRoundStartedAt(uint256 value)
external
virtual
onlyACPIMaster
returns (bool)
{
_roundStartedAt = value;
return true;
}
/**
* @dev Set totalRound value
*/
function setTotalRound(uint16 newValue)
external
virtual
onlyModerator
returns (bool)
{
_totalRound = newValue;
return true;
}
/**
* @dev Set time between two consecutive round in seconds
*/
function setRoundTime(uint256 newValue)
external
virtual
onlyModerator
returns (bool)
{
_roundTime = newValue;
return true;
}
function bid(uint16 targetRound) external payable virtual returns (bool);
/**
* @dev Start round of ACPI ending the last one.
*/
function startRound() external virtual returns (bool);
/**
* @dev Set the ACPI price when all the rounds have been done
*/
function setAcpiPrice() internal virtual {
if (_priceHistory.length == 0) return;
uint256 sum = 0;
for (uint256 i = 0; i < _priceHistory.length; i++) {
sum += _priceHistory[i] / _priceHistory.length;
}
_acpiPrice = sum;
}
/**
* @dev Set target user wins to 0 {onlyACPIMaster}
* note called after a claimTokens from the parent contract
*/
function resetAccount(address account)
external
virtual
onlyACPIMaster
returns (bool)
{
_pendingWins[account] = 0;
return true;
}
/**
* @dev Emitted when a user win a round of any ACPI
* `amount` is the amount of REG Token awarded
*/
event RoundWin(uint256 indexed amount);
/**
* @dev Emitted when a user bid
*/
event Bid(address indexed user, uint256 indexed amount);
/**
* @dev Withdraw native currency {onlyACPIMaster}
*/
function withdraw(address payable recipient, uint256 amount)
external
virtual
onlyACPIMaster
returns (bool)
{
require(recipient != address(0), "Can't burn token");
recipient.transfer(amount);
return true;
}
function pendingReturns(address account)
external
view
virtual
returns (uint256)
{}
function recoverERC20(address tokenAddress, uint256 tokenAmount)
external
virtual
onlyACPIMaster
returns (bool)
{
IERC20(tokenAddress).safeTransfer(msg.sender, tokenAmount);
return true;
}
}
|
Set target user wins to 0 {onlyACPIMaster} note called after a claimTokens from the parent contract/
|
function resetAccount(address account)
external
virtual
onlyACPIMaster
returns (bool)
{
_pendingWins[account] = 0;
return true;
}
| 898,136 |
pragma solidity 0.4.24;
import "./lib/Whitelist.sol";
import "./TraceToRequestorListInterface.sol";
/**
* @title TraceToSPList
* @dev This contract is the whitelist contract for requestors.
*/
contract TraceToRequestorList is Whitelist, TraceToRequestorListInterface{
struct meta {
string country;
string name;
string email;
string uriForMoreDetails;
string hashForMoreDetails;
}
mapping(address => meta) pendingMetaInfo;
mapping(address => meta) metaInfo;
event NewPendingRequestor(address _requestorPR);
event DetailUpdated(address _requestorPR, string detail);
/**
* @dev only requestors in the whitelist
*/
modifier onlyRequestor(){
require(isRequestorPR(msg.sender));
_;
}
/**
* @dev constructor of this contract, it will use the constructor of whiltelist contract
* @param owner Owner of this contract
*/
constructor( address owner ) Whitelist(owner) public {}
/**
* @dev add a wallet as a pending requestor (PR contract)
* @notice Information here is publicly available and is maintained for transparency
* @param _requestorPR the PR contract deployed by this requestor (PR contract)
* @param _country the country for this requestor (PR contract)
* @param _name the name for this requestor (PR contract)
* @param _email the email for this requestor (PR contract)
* @param _uriForMoreDetails the IPFS link for this requestor (PR contract)
to put more infomation regarding the Requestor.
* @param _hashForMoreDetails the hash of the JSON object in IPFS
*/
function addPendingRequestorPR(address _requestorPR, string _country, string _name, string _email, string _uriForMoreDetails, string _hashForMoreDetails)
public {
pendingMetaInfo[_requestorPR] = meta(_country, _name, _email, _uriForMoreDetails, _hashForMoreDetails);
emit NewPendingRequestor(_requestorPR);
}
/**
* @dev Approve a pending requestor (PR contract), only can be called by the owner
* @param _requestorPR the address of this requestor (PR contract)
*/
function approveRequestorPR(address _requestorPR)
public
onlyOwner{
metaInfo[_requestorPR] = pendingMetaInfo[_requestorPR];
delete pendingMetaInfo[_requestorPR];
addAddressToWhitelist(_requestorPR);
}
/**
* @dev Remove a requestor (PR contract), only can be called by the owner
* @param _requestorPR the address of this requestor (PR contract)
*/
function removeRequestorPR(address _requestorPR)
public
onlyOwner{
delete metaInfo[_requestorPR];
removeAddressFromWhitelist(_requestorPR);
}
/**
* @dev check whether an address is a requestor (PR contract)
* @param _requestorPR the address going to be checked
* @return _isRequestorPR true if the address is a requestor (PR contract)
*/
function isRequestorPR(address _requestorPR)
public
view
returns(bool _isRequestorPR){
return isWhitelisted(_requestorPR);
}
/**
* @dev check get details of a pending requestor (PR contract)
* @return _verifier the verifier wallet
* @return _country the country for this requestor (PR contract)
* @return _name the name for this requestor (PR contract)
* @return _email the email for this requestor (PR contract)
* @return _uriForMoreDetails the IPFS link for this requestor (PR contract) to put more infomation
* @return _hashForMoreDetails the hash of the JSON object in IPFS
*/
function getPendingRequestorPRMeta(address _requestorPR)
public
view
returns(string _country, string _name, string _email, string _uriForMoreDetails, string _hashForMoreDetails){
return (pendingMetaInfo[_requestorPR].country, pendingMetaInfo[_requestorPR].name, pendingMetaInfo[_requestorPR].email, pendingMetaInfo[_requestorPR].uriForMoreDetails, pendingMetaInfo[_requestorPR].hashForMoreDetails);
}
/**
* @dev check get details of a requestor (PR contract)
* @return _verifier the verifier wallet
* @return _country the country for this requestor (PR contract)
* @return _name the name for this requestor (PR contract)
* @return _email the email for this requestor (PR contract)
* @return _uriForMoreDetails the IPFS link for this requestor (PR contract) to put more infomation
* @return _hashForMoreDetails the hash of the JSON object in IPFS
*/
function getRequestorPRMeta(address _requestorPR)
public
view
returns(string _country, string _name, string _email, string _uriForMoreDetails, string _hashForMoreDetails){
return (metaInfo[_requestorPR].country, metaInfo[_requestorPR].name, metaInfo[_requestorPR].email, metaInfo[_requestorPR].uriForMoreDetails, metaInfo[_requestorPR].hashForMoreDetails);
}
}
|
check get details of a requestor (PR contract) return _verifier the verifier wallet return _country the country for this requestor (PR contract) return _name the name for this requestor (PR contract) return _email the email for this requestor (PR contract) return _uriForMoreDetails the IPFS link for this requestor (PR contract) to put more infomation return _hashForMoreDetails the hash of the JSON object in IPFS/
|
function getRequestorPRMeta(address _requestorPR)
public
view
returns(string _country, string _name, string _email, string _uriForMoreDetails, string _hashForMoreDetails){
return (metaInfo[_requestorPR].country, metaInfo[_requestorPR].name, metaInfo[_requestorPR].email, metaInfo[_requestorPR].uriForMoreDetails, metaInfo[_requestorPR].hashForMoreDetails);
}
| 12,712,065 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
// 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 contracts/Ptp.sol
pragma solidity 0.8.9;
/// @title the ptp token
/// Note initially forked from Uniswap and then upgraded to 0.8.9
contract Ptp {
/// @notice EIP-20 token name for this token
string public constant name = 'Platypus';
/// @notice EIP-20 token symbol for this token
string public constant symbol = 'PTP';
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint256 public totalSupply = 300_000_000e18; // 300M PTP
/// @notice Address which may mint new tokens
address public minter;
/// @notice The timestamp after which minting may occur
uint256 public mintingAllowedAfter;
/// @notice Minimum time between mints
uint32 public constant minimumTimeBetweenMints = 1 days * 365;
/// @notice Cap on the percentage of totalSupply that can be minted at each mint
uint8 public constant mintCap = 2;
/// @notice Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping(address => uint96) internal balances;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public immutable DOMAIN_TYPEHASH =
keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)');
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public immutable PERMIT_TYPEHASH =
keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)');
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when the minter address is changed
event MinterChanged(address minter, address newMinter);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Ptp token
* @param account The initial account to grant all the tokens
* @param minter_ The account with minting ability
* @param mintingAllowedAfter_ The timestamp after which minting may occur
*/
constructor(
address account,
address minter_,
uint256 mintingAllowedAfter_
) {
require(mintingAllowedAfter_ >= block.timestamp, 'Ptp::constructor: minting can only begin after deployment');
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter_);
mintingAllowedAfter = mintingAllowedAfter_;
}
/**
* @notice Change the minter address
* @param minter_ The address of the new minter
*/
function setMinter(address minter_) external {
require(msg.sender == minter, 'Ptp::setMinter: only the minter can change the minter address');
emit MinterChanged(minter, minter_);
minter = minter_;
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param rawAmount The number of tokens to be minted
*/
function mint(address dst, uint256 rawAmount) external {
require(msg.sender == minter, 'Ptp::mint: only the minter can mint');
require(block.timestamp >= mintingAllowedAfter, 'Ptp::mint: minting not allowed yet');
require(dst != address(0), 'Ptp::mint: cannot transfer to the zero address');
// record the mint
mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints);
// mint the amount
uint96 amount = safe96(rawAmount, 'Ptp::mint: amount exceeds 96 bits');
require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), 'Ptp::mint: exceeded mint cap');
totalSupply = safe96(SafeMath.add(totalSupply, amount), 'Ptp::mint: totalSupply exceeds 96 bits');
// transfer the amount to the recipient
balances[dst] = add96(balances[dst], amount, 'Ptp::mint: transfer amount overflows');
emit Transfer(address(0), dst, amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint256) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, 'Ptp::approve: amount exceeds 96 bits');
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(
address owner,
address spender,
uint256 rawAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
// PTP-01M fix
require(v == 27 || v == 28, 'Ptp::permit: invalid range for v');
require(
uint256(s) < 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A1,
'Ptp::permit: invalid range for s'
);
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, 'Ptp::permit: amount exceeds 96 bits');
}
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))
);
bytes32 structHash = keccak256(
abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)
);
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), 'Ptp::permit: invalid signature');
require(signatory == owner, 'Ptp::permit: unauthorized');
require(block.timestamp <= deadline, 'Ptp::permit: signature expired');
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @dev This function is expected to ALWAYS return true, or else it should throw
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, 'Ptp::transfer: amount exceeds 96 bits');
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, 'Ptp::approve: amount exceeds 96 bits');
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance = sub96(
spenderAllowance,
amount,
'Ptp::transferFrom: transfer amount exceeds spender allowance'
);
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal {
require(src != address(0), 'Ptp::_transferTokens: cannot transfer from the zero address');
require(dst != address(0), 'Ptp::_transferTokens: cannot transfer to the zero address');
balances[src] = sub96(balances[src], amount, 'Ptp::_transferTokens: transfer amount exceeds balance');
balances[dst] = add96(balances[dst], amount, 'Ptp::_transferTokens: transfer amount overflows');
emit Transfer(src, dst, amount);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
Transfer `amount` tokens from `msg.sender` to `dst` This function is expected to ALWAYS return true, or else it should throw dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
|
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, 'Ptp::transfer: amount exceeds 96 bits');
_transferTokens(msg.sender, dst, amount);
return true;
}
| 2,481,008 |
//SPDX-License-Identifier: MIT
pragma solidity =0.8.11;
pragma experimental ABIEncoderV2;
import "../interfaces/ILiquidityAccumulator.sol";
import "../libraries/ObservationLibrary.sol";
abstract contract LiquidityAccumulator is ILiquidityAccumulator {
uint256 internal constant CHANGE_PRECISION_DECIMALS = 8;
uint256 internal constant CHANGE_PRECISION = 10**CHANGE_PRECISION_DECIMALS;
uint256 public immutable updateThreshold;
uint256 public immutable minUpdateDelay;
uint256 public immutable maxUpdateDelay;
address public immutable override quoteToken;
uint256 public immutable override changePrecision = CHANGE_PRECISION;
mapping(address => AccumulationLibrary.LiquidityAccumulator) accumulations;
mapping(address => ObservationLibrary.LiquidityObservation) observations;
event Updated(
address indexed token,
address indexed quoteToken,
uint256 indexed timestamp,
uint256 tokenLiquidity,
uint256 quoteTokenLiquidity
);
constructor(
address quoteToken_,
uint256 updateThreshold_,
uint256 minUpdateDelay_,
uint256 maxUpdateDelay_
) {
quoteToken = quoteToken_;
updateThreshold = updateThreshold_;
minUpdateDelay = minUpdateDelay_;
maxUpdateDelay = maxUpdateDelay_;
}
function calculateLiquidity(
AccumulationLibrary.LiquidityAccumulator calldata firstAccumulation,
AccumulationLibrary.LiquidityAccumulator calldata secondAccumulation
) external pure virtual override returns (uint256 tokenLiquidity, uint256 quoteTokenLiquidity) {
require(firstAccumulation.timestamp != 0, "LiquidityAccumulator: TIMESTAMP_CANNOT_BE_ZERO");
uint256 deltaTime = secondAccumulation.timestamp - firstAccumulation.timestamp;
require(deltaTime != 0, "LiquidityAccumulator: DELTA_TIME_CANNOT_BE_ZERO");
unchecked {
// Underflow is desired and results in correct functionality
tokenLiquidity =
(secondAccumulation.cumulativeTokenLiquidity - firstAccumulation.cumulativeTokenLiquidity) /
deltaTime;
quoteTokenLiquidity =
(secondAccumulation.cumulativeQuoteTokenLiquidity - firstAccumulation.cumulativeQuoteTokenLiquidity) /
deltaTime;
}
}
function needsUpdate(address token) public view virtual override returns (bool) {
ObservationLibrary.LiquidityObservation storage lastObservation = observations[token];
uint256 deltaTime = block.timestamp - lastObservation.timestamp;
if (deltaTime < minUpdateDelay) return false;
// Ensures updates occur at most once every minUpdateDelay (seconds)
else if (deltaTime >= maxUpdateDelay) return true; // Ensures updates occur (optimistically) at least once every maxUpdateDelay (seconds)
/*
* maxUpdateDelay > deltaTime >= minUpdateDelay
*
* Check if the % change in liquidity warrents an update (saves gas vs. always updating on change)
*/
(uint256 tokenLiquidity, uint256 quoteTokenLiquidity) = fetchLiquidity(token);
return
changeThresholdSurpassed(tokenLiquidity, lastObservation.tokenLiquidity, updateThreshold) ||
changeThresholdSurpassed(quoteTokenLiquidity, lastObservation.quoteTokenLiquidity, updateThreshold);
}
function update(address token) external virtual override returns (bool) {
if (needsUpdate(token)) {
(uint256 tokenLiquidity, uint256 quoteTokenLiquidity) = fetchLiquidity(token);
ObservationLibrary.LiquidityObservation storage observation = observations[token];
AccumulationLibrary.LiquidityAccumulator storage accumulation = accumulations[token];
if (observation.timestamp == 0) {
/*
* Initialize
*/
observation.tokenLiquidity = tokenLiquidity;
observation.quoteTokenLiquidity = quoteTokenLiquidity;
observation.timestamp = block.timestamp;
emit Updated(token, quoteToken, block.timestamp, tokenLiquidity, quoteTokenLiquidity);
return true;
}
/*
* Update
*/
uint256 deltaTime = block.timestamp - observation.timestamp;
if (deltaTime != 0) {
unchecked {
// Overflow is desired and results in correct functionality
// We add the liquidites multiplied by the time those liquidities were present
accumulation.cumulativeTokenLiquidity += observation.tokenLiquidity * deltaTime;
accumulation.cumulativeQuoteTokenLiquidity += observation.quoteTokenLiquidity * deltaTime;
observation.tokenLiquidity = tokenLiquidity;
observation.quoteTokenLiquidity = quoteTokenLiquidity;
observation.timestamp = accumulation.timestamp = block.timestamp;
}
emit Updated(token, quoteToken, block.timestamp, tokenLiquidity, quoteTokenLiquidity);
return true;
}
}
return false;
}
function getLastAccumulation(address token)
public
view
virtual
override
returns (AccumulationLibrary.LiquidityAccumulator memory)
{
return accumulations[token];
}
function getCurrentAccumulation(address token)
public
view
virtual
override
returns (AccumulationLibrary.LiquidityAccumulator memory accumulation)
{
ObservationLibrary.LiquidityObservation storage lastObservation = observations[token];
require(lastObservation.timestamp != 0, "LiquidityAccumulator: UNINITIALIZED");
accumulation = accumulations[token]; // Load last accumulation
uint256 deltaTime = block.timestamp - lastObservation.timestamp;
if (deltaTime != 0) {
// The last observation liquidities have existed for some time, so we add that
unchecked {
// Overflow is desired and results in correct functionality
// We add the liquidites multiplied by the time those liquidities were present
accumulation.cumulativeTokenLiquidity += lastObservation.tokenLiquidity * deltaTime;
accumulation.cumulativeQuoteTokenLiquidity += lastObservation.quoteTokenLiquidity * deltaTime;
accumulation.timestamp = block.timestamp;
}
}
}
function getLastObservation(address token)
public
view
virtual
override
returns (ObservationLibrary.LiquidityObservation memory)
{
return observations[token];
}
function getCurrentObservation(address token)
public
view
virtual
override
returns (ObservationLibrary.LiquidityObservation memory observation)
{
(observation.tokenLiquidity, observation.quoteTokenLiquidity) = fetchLiquidity(token);
observation.timestamp = block.timestamp;
}
function changeThresholdSurpassed(
uint256 a,
uint256 b,
uint256 updateTheshold
) internal view virtual returns (bool) {
// Ensure a is never smaller than b
if (a < b) {
uint256 temp = a;
a = b;
b = temp;
}
// a >= b
if (a == 0) {
// a == b == 0 (since a >= b), therefore no change
return false;
} else if (b == 0) {
// (a > 0 && b == 0) => change threshold passed
// Zero to non-zero always returns true
return true;
}
unchecked {
uint256 delta = a - b; // a >= b, therefore no underflow
uint256 preciseDelta = delta * CHANGE_PRECISION;
// If the delta is so large that multiplying by CHANGE_PRECISION overflows, we assume that
// the change threshold has been surpassed.
// If our assumption is incorrect, the accumulator will be extra-up-to-date, which won't
// really break anything, but will cost more gas in keeping this accumulator updated.
if (preciseDelta < delta) return true;
uint256 change = preciseDelta / b;
return change >= updateTheshold;
}
}
function fetchLiquidity(address token)
internal
view
virtual
returns (uint256 tokenLiquidity, uint256 quoteTokenLiquidity);
}
|
Overflow is desired and results in correct functionality We add the liquidites multiplied by the time those liquidities were present
|
function update(address token) external virtual override returns (bool) {
if (needsUpdate(token)) {
(uint256 tokenLiquidity, uint256 quoteTokenLiquidity) = fetchLiquidity(token);
ObservationLibrary.LiquidityObservation storage observation = observations[token];
AccumulationLibrary.LiquidityAccumulator storage accumulation = accumulations[token];
if (observation.timestamp == 0) {
observation.tokenLiquidity = tokenLiquidity;
observation.quoteTokenLiquidity = quoteTokenLiquidity;
observation.timestamp = block.timestamp;
emit Updated(token, quoteToken, block.timestamp, tokenLiquidity, quoteTokenLiquidity);
return true;
uint256 deltaTime = block.timestamp - observation.timestamp;
if (deltaTime != 0) {
unchecked {
accumulation.cumulativeTokenLiquidity += observation.tokenLiquidity * deltaTime;
accumulation.cumulativeQuoteTokenLiquidity += observation.quoteTokenLiquidity * deltaTime;
observation.tokenLiquidity = tokenLiquidity;
observation.quoteTokenLiquidity = quoteTokenLiquidity;
observation.timestamp = accumulation.timestamp = block.timestamp;
}
emit Updated(token, quoteToken, block.timestamp, tokenLiquidity, quoteTokenLiquidity);
return true;
}
}
return false;
}
| 2,553,571 |
pragma solidity >=0.4.21 <0.6.0;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./UintUtils.sol";
import "./FissionReward.sol";
import "./FOMOReward.sol";
import "./LuckyReward.sol";
import "./FaithReward.sol";
/// @title 共振全局数据管理
/// @dev 在这里处理一些全局数据
contract ResonanceDataManage{
using SafeMath for uint256;
event AllowAccess(address indexed);
// 地址是否有访问权限
mapping(address => bool) public accessAllowed;
modifier platform() {
require(accessAllowed[msg.sender], "调用者没有调用权限");
_;
}
FissionReward fissionRewardInstance;
FOMOReward FOMORewardInstance;
LuckyReward luckyRewardInstance;
FaithReward faithRewardInstance;
// 资金池剩余额度
uint256 public fundsPool;
// 开始时间
uint256 public openingTime;
// 共振是否结束
bool crowdsaleClosed;
// 共振结束时的Step
uint256 resonanceClosedStep;
// 初始Token总额度
uint256 initBuildingTokenAmount;
// 当前轮次组建期项目方Token额度占比
uint256 buildingPercentOfParty = 50;
// 当前轮次组建期基金会投入的Token数量;
// uint256 buildingTokenFromParty;
mapping(uint256 => uint256) buildingTokenFromParty;
// 当前轮次组建期社区Token额度占比
uint256 buildingPercentOfCommunity = 50;
uint256 personalTokenLimited;// 当前轮次每个地址最多投入多少token
// step => address => 可提取ether
mapping(uint256 => mapping(address => uint256)) private ETHBalance;
// step => address => 可提取token
mapping(uint256 => mapping(address => uint256)) private tokenBalance;
mapping(uint256 => mapping(address => uint256)) FissionBalance;
mapping(uint256 => mapping(address => uint256)) FOMOBalance;
mapping(uint256 => mapping(address => uint256)) LuckyBalance;
// 用户信仰奖励余额
mapping(address => uint256) private faithRewardBalance;
constructor(
address _fassionRewardAddress,
address _FOMORewardAddress,
address _luckyRewardAddress,
address _faithRewardAddress
) public {
accessAllowed[msg.sender] = true;
// 载入奖励合约实例
fissionRewardInstance = FissionReward(_fassionRewardAddress);
FOMORewardInstance = FOMOReward(_FOMORewardAddress);
luckyRewardInstance = LuckyReward(_luckyRewardAddress);
faithRewardInstance = FaithReward(_faithRewardAddress);
}
// 设置第一轮参数
function setParamForFirstStep() public platform() {
fundsPool = UintUtils.toWei(150000000);
initBuildingTokenAmount = UintUtils.toWei(1500000);
}
function allowAccess(address _addr) public platform() {
accessAllowed[_addr] = true;
}
function denyAccess(address _addr) public platform() {
accessAllowed[_addr] = false;
}
function setFundsPool(uint256 _fundsPool) public platform() {
fundsPool = _fundsPool;
}
function getFundsPool() public view returns(uint256) {
return fundsPool;
}
function setOpeningTime(uint256 _openingTime) public platform() {
openingTime = _openingTime;
}
/// @notice 当前轮次的开始时间
function getOpeningTime() public view returns(uint256){
return openingTime;
}
function setCrowdsaleClosed(bool _crowdsaleClosed) public platform() {
crowdsaleClosed = _crowdsaleClosed;
}
function getCrowdsaleClosed() public view returns(bool) {
return crowdsaleClosed;
}
function getETHBalance(uint256 _stepIndex, address _addr) public view returns(uint256) {
return ETHBalance[_stepIndex][_addr];
}
function setETHBalance(uint256 _stepIndex, address _addr, uint256 _amount) public platform() {
ETHBalance[_stepIndex][_addr] = _amount;
}
function getTokenBalance(uint256 _stepIndex, address _addr) public view returns(uint256) {
return tokenBalance[_stepIndex][_addr];
}
function setTokenBalance(uint256 _stepIndex, address _addr, uint256 _amount) public platform() {
tokenBalance[_stepIndex][_addr] = _amount;
}
function getBuildingTokenAmount() public view returns(uint256) {
return initBuildingTokenAmount;
}
// 是否是共建期
function isBuildingPeriod() public view returns(bool){
// if(block.timestamp >= openingTime && block.timestamp <= openingTime.add(8 hours)) {
// return true;
// }else{
// return false;
// }
return true;
}
// 是否是募资期
function isFundingPeriod() public view returns(bool) {
// if(block.timestamp >= openingTime.add(8 hours) && block.timestamp <= openingTime.add(24 hours)) {
// return true;
// }else{
// return false;
// }
return true;
}
/// @notice 判断共振是否结束
/// @dev 根据共振结束条件判断共振是否结束,修改变量
/// @param raisedETH 募资期已经募集的ETH数量
/// @param softCap 当前轮次软顶
function crowdsaleIsClosed(
uint256 stepIndex,
uint256 raisedETH,
uint256 softCap
)
public
platform()
returns(bool)
{
// 1.当前轮次募资期募资额度没有达到软顶,共振结束
if(raisedETH < softCap) {
resonanceClosedStep = stepIndex;
setCrowdsaleClosed(true);
}else{
setCrowdsaleClosed(false);
// 2.消耗完资金池的总额度,共振结束
if(fundsPool == 0) {
resonanceClosedStep = stepIndex;
setCrowdsaleClosed(true);
}else{
setCrowdsaleClosed(false);
}
}
return getResonanceIsClosed();
}
/// @notice 查询共振结束时的轮次Index
function getResonanceClosedStep() public view returns(uint256){
return resonanceClosedStep;
}
/// @notice 查询共振是否结束
function getResonanceIsClosed() public view returns(bool) {
return crowdsaleClosed;
}
/// @notice 分配裂变奖励奖金
function settlementFissionReward(uint256 _stepIndex, address[] memory _fissionWinnerList, uint256 totalFissionReward)
public
platform()
{
fissionRewardInstance.dealFissionInfo(_stepIndex, _fissionWinnerList, totalFissionReward);
// 在这里累加用户可提取余额
for(uint i = 0; i < _fissionWinnerList.length; i++){
FissionBalance[_stepIndex][_fissionWinnerList[i]] = fissionRewardInstance.fissionRewardAmount(_stepIndex,_fissionWinnerList[i]);
}
}
/// @notice 分配FOMO奖励奖金
function settlementFOMOReward(uint256 _stepIndex, address[] memory _funders, uint256 totalFOMOReward)
public
platform()
{
address[] memory FOMOWinnerList = FOMORewardInstance.dealFOMOWinner(_stepIndex, _funders, totalFOMOReward);
for(uint i = 0; i < FOMOWinnerList.length; i++){
FOMOBalance[_stepIndex][FOMOWinnerList[i]] = FOMORewardInstance.FOMORewardAmount(_stepIndex, FOMOWinnerList[i]);
}
}
/// @notice 分配幸运奖励奖金
function settlementLuckyReward(uint256 _stepIndex, address[] memory _LuckyWinnerList, uint256 totalLuckyReward)
public
platform()
{
luckyRewardInstance.dealLuckyInfo(_stepIndex, _LuckyWinnerList, totalLuckyReward);
for(uint i = 0; i < _LuckyWinnerList.length; i++){
LuckyBalance[_stepIndex][_LuckyWinnerList[i]] = luckyRewardInstance.luckyRewardAmount(_stepIndex, _LuckyWinnerList[i]);
}
}
// 分配信仰奖励
function dmSettlementFaithReward(address[] memory _faithWinners, uint256 totalFaithReward)
public
platform()
returns(bool)
{
bool faithRewardFinished = faithRewardInstance.dealFaithWinner(_faithWinners, totalFaithReward);
for(uint i = 0; i < _faithWinners.length; i++){
faithRewardBalance[_faithWinners[i]] += faithRewardInstance.faithRewardAmount(_faithWinners[i]);
}
return faithRewardFinished;
}
// 获取信仰奖励金额
function getFaithRewardBalance(address _addr) public view returns(uint256) {
return faithRewardBalance[_addr];
}
function setFaithRewardBalance(address _addr, uint256 _amount) public platform() returns(uint256) {
return faithRewardBalance[_addr] = _amount;
}
/// @notice 返回可提取Token数量
function withdrawTokenAmount(uint256 _stepIndex, address _addr) public view returns (uint256) {
return tokenBalance[_stepIndex][_addr];
}
/// @notice 返回可提取的ETH数量
function withdrawETHAmount(uint256 _stepIndex, address _addr) public view returns (uint256) {
return ETHBalance[_stepIndex][_addr]
.add(FissionBalance[_stepIndex][_addr])
.add(FOMOBalance[_stepIndex][_addr])
.add(LuckyBalance[_stepIndex][_addr]);
}
function emptyTokenBalance(uint256 _stepIndex, address _addr) public platform() {
tokenBalance[_stepIndex][_addr] = 0;
}
function emptyETHBalance(uint256 _stepIndex, address _addr) public platform() {
ETHBalance[_stepIndex][_addr] = 0;
FissionBalance[_stepIndex][_addr] = 0;
FOMOBalance[_stepIndex][_addr] = 0;
LuckyBalance[_stepIndex][_addr] = 0;
}
/// @notice 查询当前轮次的裂变奖励获奖详情
/// @dev 查询某轮次裂变奖励列表
/// @param _stepIndex 轮次
function getFissionRewardInfo(uint256 _stepIndex)
public
view
returns(uint256, address[] memory, uint256[] memory)
{
return fissionRewardInstance.getFissionInfo(_stepIndex);
}
/// @notice 获取该轮次FOMO奖励详情
/// @dev 查询某轮次FOMO奖励详情
/// @param _stepIndex 轮次
function getFOMORewardIofo(uint256 _stepIndex)
public
view
returns(uint256, address[] memory, uint256[] memory)
{
return FOMORewardInstance.getFOMOWinnerInfo(_stepIndex);
}
/// @notice 获取该轮次幸运奖励详情
/// @dev 查询某轮次幸运奖励获奖人列表和奖金列表
/// @param _stepIndex 轮次
function getLuckyRewardInfo(uint256 _stepIndex)
public
view
returns(uint256, address[] memory, uint256)
{
return luckyRewardInstance.getLuckyInfo(_stepIndex);
}
/// @notice 获取信仰奖励信息
/// @dev 查询某轮次信仰奖励获奖人列表和奖金列表
function getFaithRewardInfo()
public
view
returns(uint256, address[] memory, uint256[] memory)
{
return faithRewardInstance.getFaithWinnerInfo();
}
/// @notice 获取当前轮次项目方占比
function getBuildingPercentOfParty() public view returns(uint256) {
return buildingPercentOfParty;
}
/// @notice 改变共振资金池共建比例
function updateBuildingPercent(uint256 _stepIndex) public platform() returns (bool) {
require(fundsPool > 0, "共建资金池已经消耗完毕");
if(_stepIndex == 0){
buildingTokenFromParty[_stepIndex] = initBuildingTokenAmount.mul(50).div(100);
buildingPercentOfParty = 50;
buildingPercentOfCommunity = 50;
}else{
// 随着轮次推进,社区比例每轮次+1%,项目方比例每轮-1%
if(buildingPercentOfParty < 66){
buildingPercentOfParty += 1;
buildingPercentOfCommunity -= 1;
}
// 计算当前轮次一共开放的Token数量
// 每一轮是前一轮总数的99%,也就是(每一轮开放数量 = 前一轮的开放数量 - 前一轮开放数量 * 1%)
initBuildingTokenAmount = initBuildingTokenAmount.sub(initBuildingTokenAmount.mul(1).div(100));
// 计算当前轮次基金会可投入的数量
setBuildingTokenFromParty(_stepIndex, initBuildingTokenAmount.mul(buildingPercentOfParty).div(100));
}
return true;
}
/// @notice 设置当前轮次基金会应该投入的Token数量
function setBuildingTokenFromParty(uint256 _stepIndex, uint256 _buildingPercentOfParty) internal platform() {
buildingTokenFromParty[_stepIndex] = _buildingPercentOfParty;
}
/// @notice 当前轮次基金会应该投入的Token数量
function getBuildingTokenFromParty(uint256 _stepIndex) public view returns(uint256) {
return buildingTokenFromParty[_stepIndex];
}
}
|
获取当前轮次项目方占比
|
function getBuildingPercentOfParty() public view returns(uint256) {
return buildingPercentOfParty;
}
| 13,060,231 |
pragma solidity ^0.5.0;
import "contracts/rbac/RBAC.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract AccessControl is RBAC {
using SafeMath for uint256;
address payable internal owner;
constructor() public {
paused = true; //Start paused and will change after migration
owner = msg.sender;
addRole(owner, ROLE_SYS_ADMIN);
addRole(owner, ROLE_STORE_OWNER);
}
/*
* Event Section
*/
//Event emitted when contract is upgraded
event ContractUpgrade(address newContract);
//Event emiited when a new Admin is set
event AdminAdded(address _newAdmin);
//Event emmited when the Admin privileges are removed form an Admin
event AdminRemoved(address _oldAdmin);
//Event emitted when contract is paused
event ContractPaused();
//Event emitted when contract is unpaused
event ContractUnpaused();
/*
* Variables Section
*/
//State variable to determine is contract is paused
bool public paused = false;
//For broken contract and upgrade required
address public newContractAddress;
//Mapping of Address that are admins
mapping(address => bool) public admins;
/*
* Role Section
*/
//Role for the System Administrator
string public constant ROLE_SYS_ADMIN = "role/sys-admin";
//Role for the Owners of Store
string public constant ROLE_STORE_OWNER = "role/store-owner";
/*
* Modifiers Section
*/
modifier isOwner() { require(msg.sender==owner, "Only Owner has access"); _; }
modifier isAdmin() { checkRole(msg.sender, ROLE_SYS_ADMIN); _; }
modifier notPaused() { require(!paused, "Already Paused"); _; }
modifier isPaused() { require(paused, "Is not paused"); _; }
function transferOwnership(address payable _newOwner)
public
isOwner
{
require(_newOwner != address(0), "Address can't be empty");
owner = _newOwner;
addRole(owner, ROLE_SYS_ADMIN);
addRole(owner, ROLE_STORE_OWNER);
}
//For marking contract as upgraded
function setNetAddress(address _newAddr)
external
isAdmin
isPaused
{
newContractAddress = _newAddr;
emit ContractUpgrade(_newAddr);
}
function setAdmin(address _newAdmin)
public
notPaused
isOwner
{
admins[_newAdmin] = true;
emit AdminAdded(_newAdmin);
}
function removeAdmin(address _oldAdmin)
public
isOwner
notPaused
{
admins[_oldAdmin] = false;
emit AdminAdded(_oldAdmin);
}
//Only the admin can trigger and emergency pause
function pause()
public
isAdmin
notPaused
{
paused = true;
emit ContractPaused();
}
//Only the admin can resume the system
function unpause()
public
isAdmin
isPaused
{
paused = false;
emit ContractUnpaused();
}
}
|
Only the admin can trigger and emergency pause
|
function pause()
public
isAdmin
notPaused
{
paused = true;
emit ContractPaused();
}
| 6,458,951 |
./full_match/3/0xb362B3401d95E01fAFCaEc0FaF138c69A7c6ceAC/sources/contracts/Doge.sol
|
hoge require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 senderBalance = _balances[sender];
|
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 = _tOwned[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
}
| 14,263,664 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {PermissionAdmin} from '@kyber.network/utils-sc/contracts/PermissionAdmin.sol';
import {PermissionOperators} from '@kyber.network/utils-sc/contracts/PermissionOperators.sol';
import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol';
import {IKyberGovernance} from '../interfaces/governance/IKyberGovernance.sol';
import {IRewardsDistributor} from '../interfaces/rewardDistribution/IRewardsDistributor.sol';
/**
Internal contracts to participate in KyberDAO and claim rewards for Kyber
Only accept external delegation, all reward will be transferred
*/
contract KyberInternalGovernance is PermissionOperators {
using SafeERC20 for IERC20Ext;
IERC20Ext public constant ETH_TOKEN_ADDRESS = IERC20Ext(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
address payable public rewardRecipient;
IKyberGovernance public governance;
IRewardsDistributor public rewardDistributor;
constructor(
address _admin,
address payable _rewardRecipient,
IKyberGovernance _governance,
IRewardsDistributor _rewardDistributor,
address _operator
) PermissionAdmin(_admin) {
require(_rewardRecipient != address(0), "invalid reward recipient");
require(_governance != IKyberGovernance(0), "invalid kyber governance");
require(_rewardDistributor != IRewardsDistributor(0), "invalid reward distributor");
rewardRecipient = _rewardRecipient;
governance = _governance;
rewardDistributor = _rewardDistributor;
if (_operator != address(0)) {
// consistent with current design
operators[_operator] = true;
operatorsGroup.push(_operator);
emit OperatorAdded(_operator, true);
}
}
receive() external payable {}
/**
* @dev only operator can vote, given list of proposal ids
* and an option for each proposal
*/
function vote(
uint256[] calldata proposalIds,
uint256[] calldata optionBitMasks
)
external onlyOperator
{
require(proposalIds.length == optionBitMasks.length, "invalid length");
for(uint256 i = 0; i < proposalIds.length; i++) {
governance.submitVote(proposalIds[i], optionBitMasks[i]);
}
}
/**
* @dev anyone can call to claim rewards for multiple epochs
* @dev all eth will be sent back to rewardRecipient
*/
function claimRewards(
uint256 cycle,
uint256 index,
IERC20Ext[] calldata tokens,
uint256[] calldata cumulativeAmounts,
bytes32[] calldata merkleProof
)
external
returns (uint256[] memory claimAmounts)
{
claimAmounts = rewardDistributor.claim(
cycle, index, address(this), tokens, cumulativeAmounts, merkleProof
);
for(uint256 i = 0; i < tokens.length; i++) {
uint256 bal = tokens[i] == ETH_TOKEN_ADDRESS ?
address(this).balance : tokens[i].balanceOf(address(this));
if (bal > 0) _transferToken(tokens[i], bal);
}
}
function updateRewardRecipient(address payable _newRecipient)
external onlyAdmin
{
require(_newRecipient != address(0), "invalid address");
rewardRecipient = _newRecipient;
}
/**
* @dev most likely unused, but put here for flexibility or in case a mistake in deployment
*/
function updateKyberContracts(
IKyberGovernance _governance,
IRewardsDistributor _rewardDistributor
)
external onlyAdmin
{
require(_governance != IKyberGovernance(0), "invalid kyber dao");
require(_rewardDistributor != IRewardsDistributor(0), "invalid reward distributor");
governance = _governance;
rewardDistributor = _rewardDistributor;
}
/**
* @dev allow withdraw funds of any tokens to rewardRecipient address
*/
function withdrawFund(
IERC20Ext[] calldata tokens,
uint256[] calldata amounts
) external {
require(tokens.length == amounts.length, "invalid length");
for(uint256 i = 0; i < tokens.length; i++) {
_transferToken(tokens[i], amounts[i]);
}
}
function _transferToken(IERC20Ext token, uint256 amount) internal {
if (token == ETH_TOKEN_ADDRESS) {
(bool success, ) = rewardRecipient.call { value: amount }("");
require(success, "transfer eth failed");
} else {
token.safeTransfer(rewardRecipient, amount);
}
}
}
// 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.6;
abstract contract PermissionAdmin {
address public admin;
address public pendingAdmin;
event AdminClaimed(address newAdmin, address previousAdmin);
event TransferAdminPending(address pendingAdmin);
constructor(address _admin) {
require(_admin != address(0), "admin 0");
admin = _admin;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin");
_;
}
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "new admin 0");
emit TransferAdminPending(newAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "admin 0");
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender, "not pending");
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "./PermissionAdmin.sol";
abstract contract PermissionOperators is PermissionAdmin {
uint256 private constant MAX_GROUP_SIZE = 50;
mapping(address => bool) internal operators;
address[] internal operatorsGroup;
event OperatorAdded(address newOperator, bool isAdd);
modifier onlyOperator() {
require(operators[msg.sender], "only operator");
_;
}
function getOperators() external view returns (address[] memory) {
return operatorsGroup;
}
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator], "operator exists"); // prevent duplicates.
require(operatorsGroup.length < MAX_GROUP_SIZE, "max operators");
emit OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator(address operator) public onlyAdmin {
require(operators[operator], "not operator");
operators[operator] = false;
for (uint256 i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.pop();
emit OperatorAdded(operator, false);
break;
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Interface extending ERC20 standard to include decimals() as
* it is optional in the OpenZeppelin IERC20 interface.
*/
interface IERC20Ext is IERC20 {
/**
* @dev This function is required as Kyber requires to interact
* with token.decimals() with many of its operations.
*/
function decimals() external view returns (uint8 digits);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {IExecutorWithTimelock} from './IExecutorWithTimelock.sol';
import {IVotingPowerStrategy} from './IVotingPowerStrategy.sol';
interface IKyberGovernance {
enum ProposalState {
Pending,
Canceled,
Active,
Failed,
Succeeded,
Queued,
Expired,
Executed,
Finalized
}
enum ProposalType {Generic, Binary}
/// For Binary proposal, optionBitMask is 0/1/2
/// For Generic proposal, optionBitMask is bitmask of voted options
struct Vote {
uint32 optionBitMask;
uint224 votingPower;
}
struct ProposalWithoutVote {
uint256 id;
ProposalType proposalType;
address creator;
IExecutorWithTimelock executor;
IVotingPowerStrategy strategy;
address[] targets;
uint256[] weiValues;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
string[] options;
uint256[] voteCounts;
uint256 totalVotes;
uint256 maxVotingPower;
uint256 startTime;
uint256 endTime;
uint256 executionTime;
string link;
bool executed;
bool canceled;
}
struct Proposal {
ProposalWithoutVote proposalData;
mapping(address => Vote) votes;
}
struct BinaryProposalParams {
address[] targets;
uint256[] weiValues;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
}
/**
* @dev emitted when a new binary proposal is created
* @param proposalId id of the binary proposal
* @param creator address of the creator
* @param executor ExecutorWithTimelock contract that will execute the proposal
* @param strategy votingPowerStrategy contract to calculate voting power
* @param targets list of contracts called by proposal's associated transactions
* @param weiValues list of value in wei for each propoposal's associated transaction
* @param signatures list of function signatures (can be empty) to be used
* when created the callData
* @param calldatas list of calldatas: if associated signature empty,
* calldata ready, else calldata is arguments
* @param withDelegatecalls boolean, true = transaction delegatecalls the taget,
* else calls the target
* @param startTime timestamp when vote starts
* @param endTime timestamp when vote ends
* @param link URL link of the proposal
* @param maxVotingPower max voting power for this proposal
**/
event BinaryProposalCreated(
uint256 proposalId,
address indexed creator,
IExecutorWithTimelock indexed executor,
IVotingPowerStrategy indexed strategy,
address[] targets,
uint256[] weiValues,
string[] signatures,
bytes[] calldatas,
bool[] withDelegatecalls,
uint256 startTime,
uint256 endTime,
string link,
uint256 maxVotingPower
);
/**
* @dev emitted when a new generic proposal is created
* @param proposalId id of the generic proposal
* @param creator address of the creator
* @param executor ExecutorWithTimelock contract that will execute the proposal
* @param strategy votingPowerStrategy contract to calculate voting power
* @param options list of proposal vote options
* @param startTime timestamp when vote starts
* @param endTime timestamp when vote ends
* @param link URL link of the proposal
* @param maxVotingPower max voting power for this proposal
**/
event GenericProposalCreated(
uint256 proposalId,
address indexed creator,
IExecutorWithTimelock indexed executor,
IVotingPowerStrategy indexed strategy,
string[] options,
uint256 startTime,
uint256 endTime,
string link,
uint256 maxVotingPower
);
/**
* @dev emitted when a proposal is canceled
* @param proposalId id of the proposal
**/
event ProposalCanceled(uint256 proposalId);
/**
* @dev emitted when a proposal is queued
* @param proposalId id of the proposal
* @param executionTime time when proposal underlying transactions can be executed
* @param initiatorQueueing address of the initiator of the queuing transaction
**/
event ProposalQueued(
uint256 indexed proposalId,
uint256 executionTime,
address indexed initiatorQueueing
);
/**
* @dev emitted when a proposal is executed
* @param proposalId id of the proposal
* @param initiatorExecution address of the initiator of the execution transaction
**/
event ProposalExecuted(uint256 proposalId, address indexed initiatorExecution);
/**
* @dev emitted when a vote is registered
* @param proposalId id of the proposal
* @param voter address of the voter
* @param voteOptions vote options selected by voter
* @param votingPower Power of the voter/vote
**/
event VoteEmitted(
uint256 indexed proposalId,
address indexed voter,
uint32 indexed voteOptions,
uint224 votingPower
);
/**
* @dev emitted when a vote is registered
* @param proposalId id of the proposal
* @param voter address of the voter
* @param voteOptions vote options selected by voter
* @param oldVotingPower Old power of the voter/vote
* @param newVotingPower New power of the voter/vote
**/
event VotingPowerChanged(
uint256 indexed proposalId,
address indexed voter,
uint32 indexed voteOptions,
uint224 oldVotingPower,
uint224 newVotingPower
);
event DaoOperatorTransferred(address indexed newDaoOperator);
event ExecutorAuthorized(address indexed executor);
event ExecutorUnauthorized(address indexed executor);
event VotingPowerStrategyAuthorized(address indexed strategy);
event VotingPowerStrategyUnauthorized(address indexed strategy);
/**
* @dev Function is triggered when users withdraw from staking and change voting power
*/
function handleVotingPowerChanged(
address staker,
uint256 newVotingPower,
uint256[] calldata proposalIds
) external;
/**
* @dev Creates a Binary Proposal (needs to be validated by the Proposal Validator)
* @param executor The ExecutorWithTimelock contract that will execute the proposal
* @param strategy voting power strategy of the proposal
* @param executionParams data for execution, includes
* targets list of contracts called by proposal's associated transactions
* weiValues list of value in wei for each proposal's associated transaction
* signatures list of function signatures (can be empty)
* to be used when created the callData
* calldatas list of calldatas: if associated signature empty,
* calldata ready, else calldata is arguments
* withDelegatecalls boolean, true = transaction delegatecalls the taget,
* else calls the target
* @param startTime start timestamp to allow vote
* @param endTime end timestamp of the proposal
* @param link link to the proposal description
**/
function createBinaryProposal(
IExecutorWithTimelock executor,
IVotingPowerStrategy strategy,
BinaryProposalParams memory executionParams,
uint256 startTime,
uint256 endTime,
string memory link
) external returns (uint256 proposalId);
/**
* @dev Creates a Generic Proposal
* @param executor ExecutorWithTimelock contract that will execute the proposal
* @param strategy votingPowerStrategy contract to calculate voting power
* @param options list of proposal vote options
* @param startTime timestamp when vote starts
* @param endTime timestamp when vote ends
* @param link URL link of the proposal
**/
function createGenericProposal(
IExecutorWithTimelock executor,
IVotingPowerStrategy strategy,
string[] memory options,
uint256 startTime,
uint256 endTime,
string memory link
) external returns (uint256 proposalId);
/**
* @dev Cancels a Proposal,
* either at anytime by guardian
* or when proposal is Pending/Active and threshold no longer reached
* @param proposalId id of the proposal
**/
function cancel(uint256 proposalId) external;
/**
* @dev Queue the proposal (If Proposal Succeeded)
* @param proposalId id of the proposal to queue
**/
function queue(uint256 proposalId) external;
/**
* @dev Execute the proposal (If Proposal Queued)
* @param proposalId id of the proposal to execute
**/
function execute(uint256 proposalId) external payable;
/**
* @dev Function allowing msg.sender to vote for/against a proposal
* @param proposalId id of the proposal
* @param optionBitMask vote option(s) selected
**/
function submitVote(uint256 proposalId, uint256 optionBitMask) external;
/**
* @dev Function to register the vote of user that has voted offchain via signature
* @param proposalId id of the proposal
* @param choice the bit mask of voted options
* @param v v part of the voter signature
* @param r r part of the voter signature
* @param s s part of the voter signature
**/
function submitVoteBySignature(
uint256 proposalId,
uint256 choice,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Add new addresses to the list of authorized executors
* @param executors list of new addresses to be authorized executors
**/
function authorizeExecutors(address[] calldata executors) external;
/**
* @dev Remove addresses to the list of authorized executors
* @param executors list of addresses to be removed as authorized executors
**/
function unauthorizeExecutors(address[] calldata executors) external;
/**
* @dev Add new addresses to the list of authorized strategies
* @param strategies list of new addresses to be authorized strategies
**/
function authorizeVotingPowerStrategies(address[] calldata strategies) external;
/**
* @dev Remove addresses to the list of authorized strategies
* @param strategies list of addresses to be removed as authorized strategies
**/
function unauthorizeVotingPowerStrategies(address[] calldata strategies) external;
/**
* @dev Returns whether an address is an authorized executor
* @param executor address to evaluate as authorized executor
* @return true if authorized
**/
function isExecutorAuthorized(address executor) external view returns (bool);
/**
* @dev Returns whether an address is an authorized strategy
* @param strategy address to evaluate as authorized strategy
* @return true if authorized
**/
function isVotingPowerStrategyAuthorized(address strategy) external view returns (bool);
/**
* @dev Getter the address of the guardian, that can mainly cancel proposals
* @return The address of the guardian
**/
function getDaoOperator() external view returns (address);
/**
* @dev Getter of the proposal count (the current number of proposals ever created)
* @return the proposal count
**/
function getProposalsCount() external view returns (uint256);
/**
* @dev Getter of a proposal by id
* @param proposalId id of the proposal to get
* @return the proposal as ProposalWithoutVote memory object
**/
function getProposalById(uint256 proposalId) external view returns (ProposalWithoutVote memory);
/**
* @dev Getter of the vote data of a proposal by id
* including totalVotes, voteCounts and options
* @param proposalId id of the proposal
* @return (totalVotes, voteCounts, options)
**/
function getProposalVoteDataById(uint256 proposalId)
external
view
returns (
uint256,
uint256[] memory,
string[] memory
);
/**
* @dev Getter of the Vote of a voter about a proposal
* Note: Vote is a struct: ({uint32 bitOptionMask, uint224 votingPower})
* @param proposalId id of the proposal
* @param voter address of the voter
* @return The associated Vote memory object
**/
function getVoteOnProposal(uint256 proposalId, address voter)
external
view
returns (Vote memory);
/**
* @dev Get the current state of a proposal
* @param proposalId id of the proposal
* @return The current state if the proposal
**/
function getProposalState(uint256 proposalId) external view returns (ProposalState);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol';
interface IRewardsDistributor {
event Claimed(
uint256 indexed cycle,
address indexed user,
IERC20Ext[] tokens,
uint256[] claimAmounts
);
/**
* @dev Claim accumulated rewards for a set of tokens at a given cycle number
* @param cycle cycle number
* @param index user reward info index in the array of reward info
* during merkle tree generation
* @param user wallet address of reward beneficiary
* @param tokens array of tokens claimable by reward beneficiary
* @param cumulativeAmounts cumulative token amounts claimable by reward beneficiary
* @param merkleProof merkle proof of claim
* @return claimAmounts actual claimed token amounts sent to the reward beneficiary
**/
function claim(
uint256 cycle,
uint256 index,
address user,
IERC20Ext[] calldata tokens,
uint256[] calldata cumulativeAmounts,
bytes32[] calldata merkleProof
) external returns (uint256[] memory claimAmounts);
/**
* @dev Checks whether a claim is valid or not
* @param cycle cycle number
* @param index user reward info index in the array of reward info
* during merkle tree generation
* @param user wallet address of reward beneficiary
* @param tokens array of tokens claimable by reward beneficiary
* @param cumulativeAmounts cumulative token amounts claimable by reward beneficiary
* @param merkleProof merkle proof of claim
* @return true if valid claim, false otherwise
**/
function isValidClaim(
uint256 cycle,
uint256 index,
address user,
IERC20Ext[] calldata tokens,
uint256[] calldata cumulativeAmounts,
bytes32[] calldata merkleProof
) external view returns (bool);
/**
* @dev Fetch accumulated claimed rewards for a set of tokens since the first cycle
* @param user wallet address of reward beneficiary
* @param tokens array of tokens claimed by reward beneficiary
* @return userClaimedAmounts claimed token amounts by reward beneficiary since the first cycle
**/
function getClaimedAmounts(address user, IERC20Ext[] calldata tokens)
external
view
returns (uint256[] memory userClaimedAmounts);
}
// 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;
/**
* @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 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: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {IKyberGovernance} from './IKyberGovernance.sol';
interface IExecutorWithTimelock {
/**
* @dev emitted when a new pending admin is set
* @param newPendingAdmin address of the new pending admin
**/
event NewPendingAdmin(address newPendingAdmin);
/**
* @dev emitted when a new admin is set
* @param newAdmin address of the new admin
**/
event NewAdmin(address newAdmin);
/**
* @dev emitted when a new delay (between queueing and execution) is set
* @param delay new delay
**/
event NewDelay(uint256 delay);
/**
* @dev emitted when a new (trans)action is Queued.
* @param actionHash hash of the action
* @param target address of the targeted contract
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
event QueuedAction(
bytes32 actionHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 executionTime,
bool withDelegatecall
);
/**
* @dev emitted when an action is Cancelled
* @param actionHash hash of the action
* @param target address of the targeted contract
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
event CancelledAction(
bytes32 actionHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 executionTime,
bool withDelegatecall
);
/**
* @dev emitted when an action is Cancelled
* @param actionHash hash of the action
* @param target address of the targeted contract
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
* @param resultData the actual callData used on the target
**/
event ExecutedAction(
bytes32 actionHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 executionTime,
bool withDelegatecall,
bytes resultData
);
/**
* @dev Function, called by Governance, that queue a transaction, returns action hash
* @param target smart contract target
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) external returns (bytes32);
/**
* @dev Function, called by Governance, that cancels a transaction, returns the callData executed
* @param target smart contract target
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) external payable returns (bytes memory);
/**
* @dev Function, called by Governance, that cancels a transaction, returns action hash
* @param target smart contract target
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) external returns (bytes32);
/**
* @dev Getter of the current admin address (should be governance)
* @return The address of the current admin
**/
function getAdmin() external view returns (address);
/**
* @dev Getter of the current pending admin address
* @return The address of the pending admin
**/
function getPendingAdmin() external view returns (address);
/**
* @dev Getter of the delay between queuing and execution
* @return The delay in seconds
**/
function getDelay() external view returns (uint256);
/**
* @dev Returns whether an action (via actionHash) is queued
* @param actionHash hash of the action to be checked
* keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall))
* @return true if underlying action of actionHash is queued
**/
function isActionQueued(bytes32 actionHash) external view returns (bool);
/**
* @dev Checks whether a proposal is over its grace period
* @param governance Governance contract
* @param proposalId Id of the proposal against which to test
* @return true of proposal is over grace period
**/
function isProposalOverGracePeriod(IKyberGovernance governance, uint256 proposalId)
external
view
returns (bool);
/**
* @dev Getter of grace period constant
* @return grace period in seconds
**/
function GRACE_PERIOD() external view returns (uint256);
/**
* @dev Getter of minimum delay constant
* @return minimum delay in seconds
**/
function MINIMUM_DELAY() external view returns (uint256);
/**
* @dev Getter of maximum delay constant
* @return maximum delay in seconds
**/
function MAXIMUM_DELAY() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {IWithdrawHandler} from '../staking/IWithdrawHandler.sol';
interface IVotingPowerStrategy is IWithdrawHandler {
/**
* @dev call by governance when create a proposal
*/
function handleProposalCreation(
uint256 proposalId,
uint256 startTime,
uint256 endTime
) external;
/**
* @dev call by governance when cancel a proposal
*/
function handleProposalCancellation(uint256 proposalId) external;
/**
* @dev call by governance when submitting a vote
* @param choice: unused param for future usage
* @return votingPower of voter
*/
function handleVote(
address voter,
uint256 proposalId,
uint256 choice
) external returns (uint256 votingPower);
/**
* @dev get voter's voting power given timestamp
* @dev for reading purposes and validating voting power for creating/canceling proposal in the furture
* @dev when submitVote, should call 'handleVote' instead
*/
function getVotingPower(address voter, uint256 timestamp)
external
view
returns (uint256 votingPower);
/**
* @dev validate that startTime and endTime are suitable for calculating voting power
* @dev with current version, startTime and endTime must be in the sameEpcoh
*/
function validateProposalCreation(uint256 startTime, uint256 endTime)
external
view
returns (bool);
/**
* @dev getMaxVotingPower at current time
* @dev call by governance when creating a proposal
*/
function getMaxVotingPower() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
/**
* @title Interface for callbacks hooks when user withdraws from staking contract
*/
interface IWithdrawHandler {
function handleWithdrawal(address staker, uint256 reduceAmount) external;
}
|
only operator can vote, given list of proposal ids and an option for each proposal/
|
function vote(
uint256[] calldata proposalIds,
uint256[] calldata optionBitMasks
)
external onlyOperator
{
require(proposalIds.length == optionBitMasks.length, "invalid length");
for(uint256 i = 0; i < proposalIds.length; i++) {
governance.submitVote(proposalIds[i], optionBitMasks[i]);
}
}
| 10,159,952 |
pragma solidity ^0.4.18;
// inspired by
// https://github.com/axiomzen/cryptokitties-bounty/blob/master/contracts/KittyAccessControl.sol
contract AccessControl {
/// @dev The addresses of the accounts (or contracts) that can execute actions within each roles
address public ceoAddress;
address public cooAddress;
/// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev The AccessControl constructor sets the original C roles of the contract to the sender account
function AccessControl() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Access modifier for any CLevel functionality
modifier onlyCLevel() {
require(msg.sender == ceoAddress || msg.sender == cooAddress);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @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 Pause the smart contract. Only can be called by the CEO
function pause() public onlyCEO whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Only can be called by the CEO
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
// https://github.com/dharmaprotocol/NonFungibleToken/blob/master/contracts/ERC721.sol
// https://github.com/dharmaprotocol/NonFungibleToken/blob/master/contracts/DetailedERC721.sol
/**
* Interface for required functionality in the ERC721 standard
* for non-fungible tokens.
*
* Author: Nadav Hollander (nadav at dharma.io)
*/
contract ERC721 {
// Events
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// For querying totalSupply of token.
function totalSupply() public view returns (uint256 _totalSupply);
/// 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);
/// 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);
/// @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;
// NOT IMPLEMENTED
// function getApproved(uint256 _tokenId) public view returns (address _approved);
/// 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;
/// Owner initates the transfer of the token to another account.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the token to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _tokenId) public;
///
function implementsERC721() public view returns (bool _implementsERC721);
// EXTRA
/// @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;
}
/**
* Interface for optional functionality in the ERC721 standard
* for non-fungible tokens.
*
* Author: Nadav Hollander (nadav at dharma.io)
*/
contract DetailedERC721 is ERC721 {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
// function tokenMetadata(uint256 _tokenId) public view returns (string _infoUrl);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
}
contract CryptoKittenToken is AccessControl, DetailedERC721 {
using SafeMath for uint256;
/// @dev The TokenCreated event is fired whenever a new token is created.
event TokenCreated(uint256 tokenId, string name, uint256 price, address owner);
/// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 indexed tokenId, string name, uint256 sellingPrice,
uint256 newPrice, address indexed oldOwner, address indexed newOwner);
/// @dev A mapping from tokenIds to the address that owns them. All tokens have
/// some valid owner address.
mapping (uint256 => address) private tokenIdToOwner;
/// @dev A mapping from TokenIds to the price of the token.
mapping (uint256 => uint256) private tokenIdToPrice;
/// @dev A mapping from owner address to count of tokens that address owns.
/// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) private ownershipTokenCount;
/// @dev A mapping from TokenIds to an address that has been approved to call
/// transferFrom(). Each Token can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding
mapping (uint256 => address) public tokenIdToApproved;
struct Kittens {
string name;
}
Kittens[] private kittens;
uint256 private startingPrice = 0.01 ether;
bool private erc721Enabled = false;
modifier onlyERC721() {
require(erc721Enabled);
_;
}
/// @dev Creates a new token with the given name and _price and assignes it to an _owner.
function createToken(string _name, address _owner, uint256 _price) public onlyCLevel {
require(_owner != address(0));
require(_price >= startingPrice);
_createToken(_name, _owner, _price);
}
/// @dev Creates a new token with the given name.
function createToken(string _name) public onlyCLevel {
_createToken(_name, address(this), startingPrice);
}
function _createToken(string _name, address _owner, uint256 _price) private {
Kittens memory _kitten = Kittens({
name: _name
});
uint256 newTokenId = kittens.push(_kitten) - 1;
tokenIdToPrice[newTokenId] = _price;
TokenCreated(newTokenId, _name, _price, _owner);
// This will assign ownership, and also emit the Transfer event as per ERC721 draft
_transfer(address(0), _owner, newTokenId);
}
function getToken(uint256 _tokenId) public view returns (
string _tokenName,
uint256 _price,
uint256 _nextPrice,
address _owner
) {
_tokenName = kittens[_tokenId].name;
_price = tokenIdToPrice[_tokenId];
_nextPrice = nextPriceOf(_tokenId);
_owner = tokenIdToOwner[_tokenId];
}
function getAllTokens() public view returns (
uint256[],
uint256[],
address[]
) {
uint256 total = totalSupply();
uint256[] memory prices = new uint256[](total);
uint256[] memory nextPrices = new uint256[](total);
address[] memory owners = new address[](total);
for (uint256 i = 0; i < total; i++) {
prices[i] = tokenIdToPrice[i];
nextPrices[i] = nextPriceOf(i);
owners[i] = tokenIdToOwner[i];
}
return (prices, nextPrices, owners);
}
function tokensOf(address _owner) public view returns(uint256[]) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 total = totalSupply();
uint256 resultIndex = 0;
for (uint256 i = 0; i < total; i++) {
if (tokenIdToOwner[i] == _owner) {
result[resultIndex] = i;
resultIndex++;
}
}
return result;
}
}
/// @dev This function withdraws the contract owner's cut.
/// Any amount may be withdrawn as there is no user funds.
/// User funds are immediately sent to the old owner in `purchase`
function withdrawBalance(address _to, uint256 _amount) public onlyCEO {
require(_amount <= this.balance);
if (_amount == 0) {
_amount = this.balance;
}
if (_to == address(0)) {
ceoAddress.transfer(_amount);
} else {
_to.transfer(_amount);
}
}
// Send ether and obtain the token
function purchase(uint256 _tokenId) public payable whenNotPaused {
address oldOwner = ownerOf(_tokenId);
address newOwner = msg.sender;
uint256 sellingPrice = priceOf(_tokenId);
// active tokens
require(oldOwner != address(0));
// maybe one day newOwner's logic allows this to happen
require(newOwner != address(0));
// don't buy from yourself
require(oldOwner != newOwner);
// don't sell to contracts
// but even this doesn't prevent bad contracts to become an owner of a token
require(!_isContract(newOwner));
// another check to be sure that token is active
require(sellingPrice > 0);
// min required amount check
require(msg.value >= sellingPrice);
// transfer to the new owner
_transfer(oldOwner, newOwner, _tokenId);
// update fields before emitting an event
tokenIdToPrice[_tokenId] = nextPriceOf(_tokenId);
// emit event
TokenSold(_tokenId, kittens[_tokenId].name, sellingPrice, priceOf(_tokenId), oldOwner, newOwner);
// extra ether which should be returned back to buyer
uint256 excess = msg.value.sub(sellingPrice);
// contract owner's cut which is left in contract and accesed by withdrawBalance
uint256 contractCut = sellingPrice.mul(6).div(100); // 6%
// no need to transfer if it's initial sell
if (oldOwner != address(this)) {
// transfer payment to seller minus the contract's cut
oldOwner.transfer(sellingPrice.sub(contractCut));
}
// return extra ether
if (excess > 0) {
newOwner.transfer(excess);
}
}
function priceOf(uint256 _tokenId) public view returns (uint256 _price) {
return tokenIdToPrice[_tokenId];
}
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
function nextPriceOf(uint256 _tokenId) public view returns (uint256 _nextPrice) {
uint256 _price = priceOf(_tokenId);
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
/*** ERC-721 ***/
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721() onlyCEO public {
erc721Enabled = true;
}
function totalSupply() public view returns (uint256 _totalSupply) {
_totalSupply = kittens.length;
}
function balanceOf(address _owner) public view returns (uint256 _balance) {
_balance = ownershipTokenCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
_owner = tokenIdToOwner[_tokenId];
// require(_owner != address(0));
}
function approve(address _to, uint256 _tokenId) public whenNotPaused onlyERC721 {
require(_owns(msg.sender, _tokenId));
tokenIdToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused onlyERC721 {
require(_to != address(0));
require(_owns(_from, _tokenId));
require(_approved(msg.sender, _tokenId));
_transfer(_from, _to, _tokenId);
}
function transfer(address _to, uint256 _tokenId) public whenNotPaused onlyERC721 {
require(_to != address(0));
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
function implementsERC721() public view whenNotPaused returns (bool) {
return erc721Enabled;
}
function takeOwnership(uint256 _tokenId) public whenNotPaused onlyERC721 {
require(_approved(msg.sender, _tokenId));
_transfer(tokenIdToOwner[_tokenId], msg.sender, _tokenId);
}
function name() public view returns (string _name) {
_name = "CryptoKittens";
}
function symbol() public view returns (string _symbol) {
_symbol = "CKTN";
}
/*** PRIVATES ***/
/// @dev Check for token ownership.
function _owns(address _claimant, uint256 _tokenId) private view returns (bool) {
return tokenIdToOwner[_tokenId] == _claimant;
}
/// @dev For checking approval of transfer for address _to.
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return tokenIdToApproved[_tokenId] == _to;
}
/// @dev Assigns ownership of a specific token to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of tokens is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// Transfer ownership
tokenIdToOwner[_tokenId] = _to;
// When creating new token _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete tokenIdToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev Checks if the address ia a contract or not
function _isContract(address addr) private view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
// v1.6.0
/**
* @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;
}
}
|
ERC-721 / Unlocks ERC721 behaviour, allowing for trading on third party platforms.
|
function enableERC721() onlyCEO public {
erc721Enabled = true;
}
| 5,448,129 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IHegicOptions.sol";
import "./../domain/OptionsModel.sol";
import "../../interfaces/IOptionsProtocol.sol";
import "./interfaces/IHegicPool.sol";
contract HegicAdapter is IOptionsProtocol {
using SafeMath for uint256;
struct HegicPoolInfo {
address poolAddress;
address settlementAsset; //WBTC or ETH
}
function getBuyPrice(
OptionsModel.Option memory option,
uint256 amountToBuy,
address paymentTokenAddress
) external view override returns (uint256) {
(uint256 total, , , ) = IHegicOptions(option.tokenAddress).fees(
option.expiryDate.sub(block.timestamp),
amountToBuy,
option.strikePrice,
option.optionType == OptionsModel.OptionType.PUT ? 1 : 2
);
return total;
}
function buyOptions(
OptionsModel.Option memory option,
uint256 amountToBuy,
address paymentTokenAddress
) external payable override returns (OptionsModel.OwnedOption memory) {
uint256 hegicOptionID = IHegicOptions(option.tokenAddress).create(
option.expiryDate.sub(block.timestamp),
amountToBuy,
option.strikePrice,
option.optionType == OptionsModel.OptionType.PUT ? 1 : 2
);
return OptionsModel.OwnedOption(option, amountToBuy, hegicOptionID);
}
function exerciseOptions(
OptionsModel.OwnedOption memory ownedOption,
uint256 amountToExercise,
address[] memory vaultOwners
) external payable override {
//TODO: We cant actually control how much we exercise... hegic takes a single param...?
IHegicOptions(ownedOption.option.tokenAddress).exercise(
ownedOption.protocolOptionID
);
}
function getAvailableBuyLiquidity(OptionsModel.Option memory option)
external
view
override
returns (uint256)
{
//Hegic pool can only ever reach 80% pool utilization
IHegicOptions optionsPool = IHegicOptions(option.tokenAddress);
IHegicPool pool = IHegicPool(optionsPool.pool());
uint256 unavailableLiquidity = pool.totalBalance().sub(
pool.availableBalance()
);
return pool.totalBalance().mul(80).div(100).sub(unavailableLiquidity);
}
/**
* Hegic is constant price so this is the same as the total buy liquidity available
*/
function getAvailableBuyLiquidityAtPrice(
OptionsModel.Option memory option,
uint256 maxPriceToPay,
address paymentTokenAddress
) external view override returns (uint256) {
return this.getAvailableBuyLiquidity(option);
}
/**
* Create an option given details about its attributes
* @dev tokenAddress of the option will be the Hegic poolAddress
*/
function _createOptionFromAttributes(
address baseAsset,
OptionsModel.OptionAttributes memory optionDetails,
HegicPoolInfo memory poolInfo
) internal view returns (OptionsModel.Option memory) {
return
OptionsModel.Option(
OptionsModel.OptionMarket.HEGIC,
optionDetails.optionType,
optionDetails.strikePrice,
optionDetails.expiryDate,
poolInfo.poolAddress,
poolInfo.settlementAsset,
address(0) //all options are paid for in ETH on Hegic
);
}
function createOptionsFromAttributes(
address baseAsset,
OptionsModel.OptionAttributes[] memory optionAttributeList
) public view returns (OptionsModel.Option[] memory) {
HegicPoolInfo memory poolInfo = getHegicPoolInfo(baseAsset);
OptionsModel.Option[] memory options = new OptionsModel.Option[](
optionAttributeList.length
);
for (uint256 i = 0; i < optionAttributeList.length; i++) {
_createOptionFromAttributes(
baseAsset,
optionAttributeList[i],
poolInfo
);
}
return options;
}
function getHegicPoolInfo(address baseAsset)
public
view
returns (HegicPoolInfo memory)
{
//ETH option
if (baseAsset == address(0)) {
return
HegicPoolInfo(
0xEfC0eEAdC1132A12c9487d800112693bf49EcfA2,
address(0)
);
}
//WBTC option
if (baseAsset == 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599) {
return
HegicPoolInfo(
0x20DD9e22d22dd0a6ef74a520cb08303B5faD5dE7,
0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599
);
}
//TODO: Option doesnt exist so throw?
return HegicPoolInfo(address(0), address(0));
}
}
|
Hegic pool can only ever reach 80% pool utilization
|
function getAvailableBuyLiquidity(OptionsModel.Option memory option)
external
view
override
returns (uint256)
{
IHegicOptions optionsPool = IHegicOptions(option.tokenAddress);
IHegicPool pool = IHegicPool(optionsPool.pool());
uint256 unavailableLiquidity = pool.totalBalance().sub(
pool.availableBalance()
);
return pool.totalBalance().mul(80).div(100).sub(unavailableLiquidity);
}
| 12,750,182 |
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./tools/ERC1820Client.sol";
import "./interface/ERC1820Implementer.sol";
import "./roles/MinterRole.sol";
import "./IERC1400.sol";
// Extensions
import "./extensions/tokenExtensions/IERC1400TokensValidator.sol";
import "./extensions/tokenExtensions/IERC1400TokensChecker.sol";
import "./extensions/userExtensions/IERC1400TokensSender.sol";
import "./extensions/userExtensions/IERC1400TokensRecipient.sol";
/**
* @title ERC1400
* @dev ERC1400 logic
*/
contract ERC1400 is IERC20, IERC1400, Ownable, ERC1820Client, ERC1820Implementer, MinterRole {
using SafeMath for uint256;
// Token
string constant internal ERC1400_INTERFACE_NAME = "ERC1400Token";
string constant internal ERC20_INTERFACE_NAME = "ERC20Token";
// Token extensions
string constant internal ERC1400_TOKENS_CHECKER = "ERC1400TokensChecker";
string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
// User extensions
string constant internal ERC1400_TOKENS_SENDER = "ERC1400TokensSender";
string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient";
/************************************* Token description ****************************************/
string internal _name;
string internal _symbol;
uint256 internal _granularity;
uint256 internal _totalSupply;
bool internal _migrated;
/************************************************************************************************/
/**************************************** Token behaviours **************************************/
// Indicate whether the token can still be controlled by operators or not anymore.
bool internal _isControllable;
// Indicate whether the token can still be issued by the issuer or not anymore.
bool internal _isIssuable;
/************************************************************************************************/
/********************************** ERC20 Token mappings ****************************************/
// Mapping from tokenHolder to balance.
mapping(address => uint256) internal _balances;
// Mapping from (tokenHolder, spender) to allowed value.
mapping (address => mapping (address => uint256)) internal _allowed;
/************************************************************************************************/
/**************************************** Documents *********************************************/
struct Doc {
string docURI;
bytes32 docHash;
}
// Mapping for token URIs.
mapping(bytes32 => Doc) internal _documents;
/************************************************************************************************/
/*********************************** Partitions mappings ***************************************/
// List of partitions.
bytes32[] internal _totalPartitions;
// Mapping from partition to their index.
mapping (bytes32 => uint256) internal _indexOfTotalPartitions;
// Mapping from partition to global balance of corresponding partition.
mapping (bytes32 => uint256) internal _totalSupplyByPartition;
// Mapping from tokenHolder to their partitions.
mapping (address => bytes32[]) internal _partitionsOf;
// Mapping from (tokenHolder, partition) to their index.
mapping (address => mapping (bytes32 => uint256)) internal _indexOfPartitionsOf;
// Mapping from (tokenHolder, partition) to balance of corresponding partition.
mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition;
// List of token default partitions (for ERC20 compatibility).
bytes32[] internal _defaultPartitions;
/************************************************************************************************/
/********************************* Global operators mappings ************************************/
// Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC]
mapping(address => mapping(address => bool)) internal _authorizedOperator;
// Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC]
address[] internal _controllers;
// Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC]
mapping(address => bool) internal _isController;
/************************************************************************************************/
/******************************** Partition operators mappings **********************************/
// Mapping from (partition, tokenHolder, spender) to allowed value. [TOKEN-HOLDER-SPECIFIC]
mapping(bytes32 => mapping (address => mapping (address => uint256))) internal _allowedByPartition;
// Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC]
mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition;
// Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC]
mapping (bytes32 => address[]) internal _controllersByPartition;
// Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC]
mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition;
/************************************************************************************************/
/***************************************** Modifiers ********************************************/
/**
* @dev Modifier to verify if token is issuable.
*/
modifier isIssuableToken() {
require(_isIssuable, "55"); // 0x55 funds locked (lockup period)
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not migrated.
*/
modifier isNotMigratedToken() {
require(!_migrated, "54"); // 0x54 transfers halted (contract paused)
_;
}
/**
* @dev Modifier to verifiy if sender is a minter.
*/
modifier onlyMinter() override {
require(isMinter(msg.sender) || owner() == _msgSender());
_;
}
/************************************************************************************************/
/**************************** Events (additional - not mandatory) *******************************/
event ApprovalByPartition(bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value);
/************************************************************************************************/
/**
* @dev Initialize ERC1400 + register the contract implementation in ERC1820Registry.
* @param name Name of the token.
* @param symbol Symbol of the token.
* @param granularity Granularity of the token.
* @param controllers Array of initial controllers.
* @param defaultPartitions Partitions chosen by default, when partition is
* not specified, like the case ERC20 tranfers.
*/
constructor(
string memory name,
string memory symbol,
uint256 granularity,
address[] memory controllers,
bytes32[] memory defaultPartitions
)
public
{
_name = name;
_symbol = symbol;
_totalSupply = 0;
require(granularity >= 1); // Constructor Blocked - Token granularity can not be lower than 1
_granularity = granularity;
_setControllers(controllers);
_defaultPartitions = defaultPartitions;
_isControllable = true;
_isIssuable = true;
// Register contract in ERC1820 registry
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, address(this));
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this));
// Indicate token verifies ERC1400 and ERC20 interfaces
ERC1820Implementer._setInterface(ERC1400_INTERFACE_NAME); // For migration
ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); // For migration
}
/************************************************************************************************/
/****************************** EXTERNAL FUNCTIONS (ERC20 INTERFACE) ****************************/
/************************************************************************************************/
/**
* @dev Get the total number of issued tokens.
* @return Total supply of tokens currently in circulation.
*/
function totalSupply() external override view returns (uint256) {
return _totalSupply;
}
/**
* @dev Get the balance of the account with address 'tokenHolder'.
* @param tokenHolder Address for which the balance is returned.
* @return Amount of token held by 'tokenHolder' in the token contract.
*/
function balanceOf(address tokenHolder) external override view returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev Transfer token for a specified address.
* @param to The address to transfer to.
* @param value The value to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint256 value) external override returns (bool) {
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, "");
return true;
}
/**
* @dev Check the value 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 value of tokens still available for the spender.
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean that indicates if the operation was successful.
*/
function approve(address spender, uint256 value) external override returns (bool) {
require(spender != address(0), "56"); // 0x56 invalid sender
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address which you want to transfer tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address from, address to, uint256 value) external override returns (bool) {
require( _isOperator(msg.sender, from)
|| (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowed[from][msg.sender] >= value) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
} else {
_allowed[from][msg.sender] = 0;
}
_transferByDefaultPartitions(msg.sender, from, to, value, "");
return true;
}
/************************************************************************************************/
/****************************** EXTERNAL FUNCTIONS (ERC1400 INTERFACE) **************************/
/************************************************************************************************/
/************************************* Document Management **************************************/
/**
* @dev Access a document associated with the token.
* @param name Short name (represented as a bytes32) associated to the document.
* @return Requested document + document hash.
*/
function getDocument(bytes32 name) external override view returns (string memory, bytes32) {
require(bytes(_documents[name].docURI).length != 0); // Action Blocked - Empty document
return (
_documents[name].docURI,
_documents[name].docHash
);
}
/**
* @dev Associate a document with the token.
* @param name Short name (represented as a bytes32) associated to the document.
* @param uri Document content.
* @param documentHash Hash of the document [optional parameter].
*/
function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external override {
require(_isController[msg.sender]);
_documents[name] = Doc({
docURI: uri,
docHash: documentHash
});
emit Document(name, uri, documentHash);
}
/************************************************************************************************/
/************************************** Token Information ***************************************/
/**
* @dev Get balance of a tokenholder for a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which the balance is returned.
* @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract.
*/
function balanceOfByPartition(bytes32 partition, address tokenHolder) external override view returns (uint256) {
return _balanceOfByPartition[tokenHolder][partition];
}
/**
* @dev Get partitions index of a tokenholder.
* @param tokenHolder Address for which the partitions index are returned.
* @return Array of partitions index of 'tokenHolder'.
*/
function partitionsOf(address tokenHolder) external override view returns (bytes32[] memory) {
return _partitionsOf[tokenHolder];
}
/************************************************************************************************/
/****************************************** Transfers *******************************************/
/**
* @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder.
*/
function transferWithData(address to, uint256 value, bytes calldata data) external override {
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, data);
}
/**
* @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'.
* @param from Token holder (or 'address(0)' to set from to 'msg.sender').
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, and intended for the token holder ('from').
*/
function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external override virtual {
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_transferByDefaultPartitions(msg.sender, from, to, value, data);
}
/************************************************************************************************/
/********************************** Partition Token Transfers ***********************************/
/**
* @dev Transfer tokens from a specific partition.
* @param partition Name of the partition.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder.
* @return Destination partition.
*/
function transferByPartition(
bytes32 partition,
address to,
uint256 value,
bytes calldata data
)
external
override
returns (bytes32)
{
return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, "");
}
/**
* @dev Transfer tokens from a specific partition through an operator.
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator.
* @return Destination partition.
*/
function operatorTransferByPartition(
bytes32 partition,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
)
external
override
returns (bytes32)
{
require(_isOperatorForPartition(partition, msg.sender, from)
|| (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowedByPartition[partition][from][msg.sender] >= value) {
_allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value);
} else {
_allowedByPartition[partition][from][msg.sender] = 0;
}
return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData);
}
/************************************************************************************************/
/************************************* Controller Operation *************************************/
/**
* @dev Know if the token can be controlled by operators.
* If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future.
* @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore.
*/
function isControllable() external override view returns (bool) {
return _isControllable;
}
/************************************************************************************************/
/************************************* Operator Management **************************************/
/**
* @dev Set a third party operator address as an operator of 'msg.sender' to transfer
* and redeem tokens on its behalf.
* @param operator Address to set as an operator for 'msg.sender'.
*/
function authorizeOperator(address operator) external override {
require(operator != msg.sender);
_authorizedOperator[operator][msg.sender] = true;
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev Remove the right of the operator address to be an operator for 'msg.sender'
* and to transfer and redeem tokens on its behalf.
* @param operator Address to rescind as an operator for 'msg.sender'.
*/
function revokeOperator(address operator) external override {
require(operator != msg.sender);
_authorizedOperator[operator][msg.sender] = false;
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev Set 'operator' as an operator for 'msg.sender' for a given partition.
* @param partition Name of the partition.
* @param operator Address to set as an operator for 'msg.sender'.
*/
function authorizeOperatorByPartition(bytes32 partition, address operator) external override {
_authorizedOperatorByPartition[msg.sender][partition][operator] = true;
emit AuthorizedOperatorByPartition(partition, operator, msg.sender);
}
/**
* @dev Remove the right of the operator address to be an operator on a given
* partition for 'msg.sender' and to transfer and redeem tokens on its behalf.
* @param partition Name of the partition.
* @param operator Address to rescind as an operator on given partition for 'msg.sender'.
*/
function revokeOperatorByPartition(bytes32 partition, address operator) external override {
_authorizedOperatorByPartition[msg.sender][partition][operator] = false;
emit RevokedOperatorByPartition(partition, operator, msg.sender);
}
/************************************************************************************************/
/************************************* Operator Information *************************************/
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder address.
* @param operator Address which may be an operator of tokenHolder.
* @param tokenHolder Address of a token holder which may have the operator address as an operator.
* @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise.
*/
function isOperator(address operator, address tokenHolder) external override view returns (bool) {
return _isOperator(operator, tokenHolder);
}
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder
* address for the given partition.
* @param partition Name of the partition.
* @param operator Address which may be an operator of tokenHolder for the given partition.
* @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition.
* @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise.
*/
function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external override view returns (bool) {
return _isOperatorForPartition(partition, operator, tokenHolder);
}
/************************************************************************************************/
/**************************************** Token Issuance ****************************************/
/**
* @dev Know if new tokens can be issued in the future.
* @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore.
*/
function isIssuable() external override view returns (bool) {
return _isIssuable;
}
/**
* @dev Issue tokens from default partition.
* @param tokenHolder Address for which we want to issue tokens.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, by the issuer.
*/
function issue(address tokenHolder, uint256 value, bytes calldata data)
external
override
onlyMinter
isIssuableToken
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
_issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data);
}
/**
* @dev Issue tokens from a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which we want to issue tokens.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, by the issuer.
*/
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data)
external
override
onlyMinter
isIssuableToken
{
_issueByPartition(partition, msg.sender, tokenHolder, value, data);
}
/************************************************************************************************/
/*************************************** Token Redemption ***************************************/
/**
* @dev Redeem the amount of tokens from the address 'msg.sender'.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption, by the token holder.
*/
function redeem(uint256 value, bytes calldata data)
external
override
{
_redeemByDefaultPartitions(msg.sender, msg.sender, value, data);
}
/**
* @dev Redeem the amount of tokens on behalf of the address from.
* @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender).
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function redeemFrom(address from, uint256 value, bytes calldata data)
external
override
virtual
{
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_redeemByDefaultPartitions(msg.sender, from, value, data);
}
/**
* @dev Redeem tokens of a specific partition.
* @param partition Name of the partition.
* @param value Number of tokens redeemed.
* @param data Information attached to the redemption, by the redeemer.
*/
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data)
external
override
{
_redeemByPartition(partition, msg.sender, msg.sender, value, data, "");
}
/**
* @dev Redeem tokens of a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which we want to redeem tokens.
* @param value Number of tokens redeemed
* @param operatorData Information attached to the redemption, by the operator.
*/
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData)
external
override
{
require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent)
_redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData);
}
/************************************************************************************************/
/************************************************************************************************/
/************************ EXTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/
/************************************************************************************************/
/************************************ Token description *****************************************/
/**
* @dev Get the name of the token, e.g., "MyToken".
* @return Name of the token.
*/
function name() external view returns(string memory) {
return _name;
}
/**
* @dev Get the symbol of the token, e.g., "MYT".
* @return Symbol of the token.
*/
function symbol() external view returns(string memory) {
return _symbol;
}
/**
* @dev Get the number of decimals of the token.
* @return The number of decimals of the token. For retrocompatibility, decimals are forced to 18 in ERC1400.
*/
function decimals() external pure returns(uint8) {
return uint8(18);
}
/**
* @dev Get the smallest part of the token that’s not divisible.
* @return The smallest non-divisible part of the token.
*/
function granularity() external view returns(uint256) {
return _granularity;
}
/**
* @dev Get list of existing partitions.
* @return Array of all exisiting partitions.
*/
function totalPartitions() external view returns (bytes32[] memory) {
return _totalPartitions;
}
/**
* @dev Get the total number of issued tokens for a given partition.
* @param partition Name of the partition.
* @return Total supply of tokens currently in circulation, for a given partition.
*/
function totalSupplyByPartition(bytes32 partition) external view returns (uint256) {
return _totalSupplyByPartition[partition];
}
/************************************************************************************************/
/**************************************** Token behaviours **************************************/
/**
* @dev Definitely renounce the possibility to control tokens on behalf of tokenHolders.
* Once set to false, '_isControllable' can never be set to 'true' again.
*/
function renounceControl() external onlyOwner {
_isControllable = false;
}
/**
* @dev Definitely renounce the possibility to issue new tokens.
* Once set to false, '_isIssuable' can never be set to 'true' again.
*/
function renounceIssuance() external onlyOwner {
_isIssuable = false;
}
/************************************************************************************************/
/************************************ Token controllers *****************************************/
/**
* @dev Get the list of controllers as defined by the token contract.
* @return List of addresses of all the controllers.
*/
function controllers() external view returns (address[] memory) {
return _controllers;
}
/**
* @dev Get controllers for a given partition.
* @param partition Name of the partition.
* @return Array of controllers for partition.
*/
function controllersByPartition(bytes32 partition) external view returns (address[] memory) {
return _controllersByPartition[partition];
}
/**
* @dev Set list of token controllers.
* @param operators Controller addresses.
*/
function setControllers(address[] calldata operators) external onlyOwner {
_setControllers(operators);
}
/**
* @dev Set list of token partition controllers.
* @param partition Name of the partition.
* @param operators Controller addresses.
*/
function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner {
_setPartitionControllers(partition, operators);
}
/************************************************************************************************/
/********************************* Token default partitions *************************************/
/**
* @dev Get default partitions to transfer from.
* Function used for ERC20 retrocompatibility.
* For example, a security token may return the bytes32("unrestricted").
* @return Array of default partitions.
*/
function getDefaultPartitions() external view returns (bytes32[] memory) {
return _defaultPartitions;
}
/**
* @dev Set default partitions to transfer from.
* Function used for ERC20 retrocompatibility.
* @param partitions partitions to use by default when not specified.
*/
function setDefaultPartitions(bytes32[] calldata partitions) external onlyOwner {
_defaultPartitions = partitions;
}
/************************************************************************************************/
/******************************** Partition Token Allowances ************************************/
/**
* @dev Check the value of tokens that an owner allowed to a spender.
* @param partition Name of the partition.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the value of tokens still available for the spender.
*/
function allowanceByPartition(bytes32 partition, address owner, address spender) external view returns (uint256) {
return _allowedByPartition[partition][owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'.
* @param partition Name of the partition.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean that indicates if the operation was successful.
*/
function approveByPartition(bytes32 partition, address spender, uint256 value) external returns (bool) {
require(spender != address(0), "56"); // 0x56 invalid sender
_allowedByPartition[partition][msg.sender][spender] = value;
emit ApprovalByPartition(partition, msg.sender, spender, value);
return true;
}
/************************************************************************************************/
/************************************** Token extension *****************************************/
/**
* @dev Set token extension contract address.
* The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces.
* If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed.
* @param extension Address of the extension contract.
* @param interfaceLabel Interface label of extension contract.
* @param removeOldExtensionRoles If set to 'true', the roles of the old extension(minter, controller) will be removed extension.
* @param addMinterRoleForExtension If set to 'true', the extension contract will be added as minter.
* @param addControllerRoleForExtension If set to 'true', the extension contract will be added as controller.
*/
function setTokenExtension(address extension, string calldata interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) external onlyOwner {
_setTokenExtension(extension, interfaceLabel, removeOldExtensionRoles, addMinterRoleForExtension, addControllerRoleForExtension);
}
/************************************************************************************************/
/************************************* Token migration ******************************************/
/**
* @dev Migrate contract.
*
* ===> CAUTION: DEFINITIVE ACTION
*
* This function shall be called once a new version of the smart contract has been created.
* Once this function is called:
* - The address of the new smart contract is set in ERC1820 registry
* - If the choice is definitive, the current smart contract is turned off and can never be used again
*
* @param newContractAddress Address of the new version of the smart contract.
* @param definitive If set to 'true' the contract is turned off definitely.
*/
function migrate(address newContractAddress, bool definitive) external onlyOwner {
_migrate(newContractAddress, definitive);
}
/************************************************************************************************/
/************************************************************************************************/
/************************************* INTERNAL FUNCTIONS ***************************************/
/************************************************************************************************/
/**************************************** Token Transfers ***************************************/
/**
* @dev Perform the transfer of tokens.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
*/
function _transferWithData(
address from,
address to,
uint256 value
)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(to != address(0), "57"); // 0x57 invalid receiver
require(_balances[from] >= value, "52"); // 0x52 insufficient balance
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value); // ERC20 retrocompatibility
}
/**
* @dev Transfer tokens from a specific partition.
* @param fromPartition Partition of the tokens to transfer.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return Destination partition.
*/
function _transferByPartition(
bytes32 fromPartition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
returns (bytes32)
{
require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance
bytes32 toPartition = fromPartition;
if(operatorData.length != 0 && data.length >= 64) {
toPartition = _getDestinationPartition(fromPartition, data);
}
_callSenderExtension(fromPartition, operator, from, to, value, data, operatorData);
_callTokenExtension(fromPartition, operator, from, to, value, data, operatorData);
_removeTokenFromPartition(from, fromPartition, value);
_transferWithData(from, to, value);
_addTokenToPartition(to, toPartition, value);
_callRecipientExtension(toPartition, operator, from, to, value, data, operatorData);
emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData);
if(toPartition != fromPartition) {
emit ChangedPartition(fromPartition, toPartition, value);
}
return toPartition;
}
/**
* @dev Transfer tokens from default partitions.
* Function used for ERC20 retrocompatibility.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION].
*/
function _transferByDefaultPartitions(
address operator,
address from,
address to,
uint256 value,
bytes memory data
)
internal
{
require(_defaultPartitions.length != 0, "55"); // // 0x55 funds locked (lockup period)
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, "");
_remainingValue = 0;
break;
} else if (_localBalance != 0) {
_transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
require(_remainingValue == 0, "52"); // 0x52 insufficient balance
}
/**
* @dev Retrieve the destination partition from the 'data' field.
* By convention, a partition change is requested ONLY when 'data' starts
* with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
* When the flag is detected, the destination tranche is extracted from the
* 32 bytes following the flag.
* @param fromPartition Partition of the tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @return toPartition Destination partition.
*/
function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) {
bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
bytes32 flag;
assembly {
flag := mload(add(data, 32))
}
if(flag == changePartitionFlag) {
assembly {
toPartition := mload(add(data, 64))
}
} else {
toPartition = fromPartition;
}
}
/**
* @dev Remove a token from a specific partition.
* @param from Token holder.
* @param partition Name of the partition.
* @param value Number of tokens to transfer.
*/
function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal {
_balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value);
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value);
// If the total supply is zero, finds and deletes the partition.
if(_totalSupplyByPartition[partition] == 0) {
uint256 index1 = _indexOfTotalPartitions[partition];
require(index1 > 0, "50"); // 0x50 transfer failure
// move the last item into the index being vacated
bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1];
_totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing
_indexOfTotalPartitions[lastValue] = index1;
//_totalPartitions.length -= 1;
_totalPartitions.pop();
_indexOfTotalPartitions[partition] = 0;
}
// If the balance of the TokenHolder's partition is zero, finds and deletes the partition.
if(_balanceOfByPartition[from][partition] == 0) {
uint256 index2 = _indexOfPartitionsOf[from][partition];
require(index2 > 0, "50"); // 0x50 transfer failure
// move the last item into the index being vacated
bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1];
_partitionsOf[from][index2 - 1] = lastValue; // adjust for 1-based indexing
_indexOfPartitionsOf[from][lastValue] = index2;
//_partitionsOf[from].length -= 1;
_partitionsOf[from].pop();
_indexOfPartitionsOf[from][partition] = 0;
}
}
/**
* @dev Add a token to a specific partition.
* @param to Token recipient.
* @param partition Name of the partition.
* @param value Number of tokens to transfer.
*/
function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal {
if(value != 0) {
if (_indexOfPartitionsOf[to][partition] == 0) {
_partitionsOf[to].push(partition);
_indexOfPartitionsOf[to][partition] = _partitionsOf[to].length;
}
_balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value);
if (_indexOfTotalPartitions[partition] == 0) {
_totalPartitions.push(partition);
_indexOfTotalPartitions[partition] = _totalPartitions.length;
}
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value);
}
}
/**
* @dev Check if 'value' is multiple of the granularity.
* @param value The quantity that want's to be checked.
* @return 'true' if 'value' is a multiple of the granularity.
*/
function _isMultiple(uint256 value) internal view returns(bool) {
return(value.div(_granularity).mul(_granularity) == value);
}
/************************************************************************************************/
/****************************************** Hooks ***********************************************/
/**
* @dev Check for 'ERC1400TokensSender' user extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
*/
function _callSenderExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address senderImplementation;
senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER);
if (senderImplementation != address(0)) {
IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/**
* @dev Check for 'ERC1400TokensValidator' token extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
*/
function _callTokenExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address validatorImplementation;
validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR);
if (validatorImplementation != address(0)) {
IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/**
* @dev Check for 'ERC1400TokensRecipient' user extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance increase (through transfer or issuance).
* @param from Token holder for a transfer and 0x for an issuance.
* @param to Token recipient.
* @param value Number of tokens the recipient balance is increased by.
* @param data Extra information, intended for the token holder ('from').
* @param operatorData Extra information attached by the operator (if any).
*/
function _callRecipientExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
virtual
{
address recipientImplementation;
recipientImplementation = interfaceAddr(to, ERC1400_TOKENS_RECIPIENT);
if (recipientImplementation != address(0)) {
IERC1400TokensRecipient(recipientImplementation).tokensReceived(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/************************************************************************************************/
/************************************* Operator Information *************************************/
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder address.
* @param operator Address which may be an operator of 'tokenHolder'.
* @param tokenHolder Address of a token holder which may have the 'operator' address as an operator.
* @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise.
*/
function _isOperator(address operator, address tokenHolder) internal view returns (bool) {
return (operator == tokenHolder
|| _authorizedOperator[operator][tokenHolder]
|| (_isControllable && _isController[operator])
);
}
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder
* address for the given partition.
* @param partition Name of the partition.
* @param operator Address which may be an operator of tokenHolder for the given partition.
* @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition.
* @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise.
*/
function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) {
return (_isOperator(operator, tokenHolder)
|| _authorizedOperatorByPartition[tokenHolder][partition][operator]
|| (_isControllable && _isControllerByPartition[partition][operator])
);
}
/************************************************************************************************/
/**************************************** Token Issuance ****************************************/
/**
* @dev Perform the issuance of tokens.
* @param operator Address which triggered the issuance.
* @param to Token recipient.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, and intended for the recipient (to).
*/
function _issue(address operator, address to, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(to != address(0), "57"); // 0x57 invalid receiver
_totalSupply = _totalSupply.add(value);
_balances[to] = _balances[to].add(value);
emit Issued(operator, to, value, data);
emit Transfer(address(0), to, value); // ERC20 retrocompatibility
}
/**
* @dev Issue tokens from a specific partition.
* @param toPartition Name of the partition.
* @param operator The address performing the issuance.
* @param to Token recipient.
* @param value Number of tokens to issue.
* @param data Information attached to the issuance.
*/
function _issueByPartition(
bytes32 toPartition,
address operator,
address to,
uint256 value,
bytes memory data
)
internal
{
_callTokenExtension(toPartition, operator, address(0), to, value, data, "");
_issue(operator, to, value, data);
_addTokenToPartition(to, toPartition, value);
_callRecipientExtension(toPartition, operator, address(0), to, value, data, "");
emit IssuedByPartition(toPartition, operator, to, value, data, "");
}
/************************************************************************************************/
/*************************************** Token Redemption ***************************************/
/**
* @dev Perform the token redemption.
* @param operator The address performing the redemption.
* @param from Token holder whose tokens will be redeemed.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function _redeem(address operator, address from, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(from != address(0), "56"); // 0x56 invalid sender
require(_balances[from] >= value, "52"); // 0x52 insufficient balance
_balances[from] = _balances[from].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Redeemed(operator, from, value, data);
emit Transfer(from, address(0), value); // ERC20 retrocompatibility
}
/**
* @dev Redeem tokens of a specific partition.
* @param fromPartition Name of the partition.
* @param operator The address performing the redemption.
* @param from Token holder whose tokens will be redeemed.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
* @param operatorData Information attached to the redemption, by the operator (if any).
*/
function _redeemByPartition(
bytes32 fromPartition,
address operator,
address from,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance
_callSenderExtension(fromPartition, operator, from, address(0), value, data, operatorData);
_callTokenExtension(fromPartition, operator, from, address(0), value, data, operatorData);
_removeTokenFromPartition(from, fromPartition, value);
_redeem(operator, from, value, data);
emit RedeemedByPartition(fromPartition, operator, from, value, operatorData);
}
/**
* @dev Redeem tokens from a default partitions.
* @param operator The address performing the redeem.
* @param from Token holder.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function _redeemByDefaultPartitions(
address operator,
address from,
uint256 value,
bytes memory data
)
internal
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, "");
_remainingValue = 0;
break;
} else {
_redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
require(_remainingValue == 0, "52"); // 0x52 insufficient balance
}
/************************************************************************************************/
/************************************** Transfer Validity ***************************************/
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param payload Payload of the initial transaction.
* @param partition Name of the partition.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function _canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData)
internal
view
returns (bytes1, bytes32, bytes32)
{
address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER);
if((checksImplementation != address(0))) {
return IERC1400TokensChecker(checksImplementation).canTransferByPartition(payload, partition, operator, from, to, value, data, operatorData);
}
else {
return(hex"00", "", partition);
}
}
/************************************************************************************************/
/************************************************************************************************/
/************************ INTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/
/************************************************************************************************/
/************************************ Token controllers *****************************************/
/**
* @dev Set list of token controllers.
* @param operators Controller addresses.
*/
function _setControllers(address[] memory operators) internal {
for (uint i = 0; i<_controllers.length; i++){
_isController[_controllers[i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isController[operators[j]] = true;
}
_controllers = operators;
}
/**
* @dev Set list of token partition controllers.
* @param partition Name of the partition.
* @param operators Controller addresses.
*/
function _setPartitionControllers(bytes32 partition, address[] memory operators) internal {
for (uint i = 0; i<_controllersByPartition[partition].length; i++){
_isControllerByPartition[partition][_controllersByPartition[partition][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isControllerByPartition[partition][operators[j]] = true;
}
_controllersByPartition[partition] = operators;
}
/************************************************************************************************/
/************************************** Token extension *****************************************/
/**
* @dev Set token extension contract address.
* The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces.
* If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed.
* @param extension Address of the extension contract.
* @param interfaceLabel Interface label of extension contract.
* @param removeOldExtensionRoles If set to 'true', the roles of the old extension(minter, controller) will be removed extension.
* @param addMinterRoleForExtension If set to 'true', the extension contract will be added as minter.
* @param addControllerRoleForExtension If set to 'true', the extension contract will be added as controller.
*/
function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal {
address oldExtension = interfaceAddr(address(this), interfaceLabel);
if (oldExtension != address(0) && removeOldExtensionRoles) {
if(isMinter(oldExtension)) {
_removeMinter(oldExtension);
}
_isController[oldExtension] = false;
}
ERC1820Client.setInterfaceImplementation(interfaceLabel, extension);
if(addMinterRoleForExtension && !isMinter(extension)) {
_addMinter(extension);
}
if (addControllerRoleForExtension) {
_isController[extension] = true;
}
}
/************************************************************************************************/
/************************************* Token migration ******************************************/
/**
* @dev Migrate contract.
*
* ===> CAUTION: DEFINITIVE ACTION
*
* This function shall be called once a new version of the smart contract has been created.
* Once this function is called:
* - The address of the new smart contract is set in ERC1820 registry
* - If the choice is definitive, the current smart contract is turned off and can never be used again
*
* @param newContractAddress Address of the new version of the smart contract.
* @param definitive If set to 'true' the contract is turned off definitely.
*/
function _migrate(address newContractAddress, bool definitive) internal {
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress);
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress);
if(definitive) {
_migrated = true;
}
}
/************************************************************************************************/
}
|
Redeem tokens from a default partitions. operator The address performing the redeem. from Token holder. value Number of tokens to redeem. data Information attached to the redemption./
|
function _redeemByDefaultPartitions(
address operator,
address from,
uint256 value,
bytes memory data
)
internal
{
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, "");
_remainingValue = 0;
break;
_redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
}
| 7,232,150 |
pragma solidity 0.6.12;
/**
* @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 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));
}
}
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/*
* @dev 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 ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_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;
}
/**
* @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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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: GPL-3.0-only
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface INBUNIERC20 {
/**
* @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);
event Log(string log);
}
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Encore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract EncoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeMath for uint;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of ENCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accEncorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accEncorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. ENCOREs to distribute per block.
uint256 accEncorePerShare; // Accumulated ENCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
bool depositable; // Is this pool depositable?
mapping(address => mapping(address => uint256)) allowance;
}
// The ENCORE TOKEN!
INBUNIERC20 public encore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
address public ENCOREETHLPBurnAddress;
mapping(address=>bool) public voidWithdrawList;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _encore,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 1666;
encore = _encore;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable,
bool _depositable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accEncorePerShare: 0,
withdrawable : _withdrawable,
depositable : _depositable
})
);
}
// Update the given pool's ENCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
function setPoolDepositable(
uint256 _pid,
bool _depositable
) public onlyOwner {
poolInfo[_pid].depositable = _depositable;
}
// Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
uint16 public DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 2000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
function editVoidWithdrawList(address _user, bool _voidfee) public onlyOwner {
voidWithdrawList[_user] = _voidfee;
}
// ----
// Function that adds pending rewards, called by the ENCORE token.
// ----
uint256 private encoreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = encore.balanceOf(address(this)).sub(encoreBalance);
if(newRewards > 0) {
encoreBalance = encore.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public returns (uint256 encoreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
encoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 encoreRewardFee = encoreRewardWhole.mul(DEV_FEE).div(10000);
uint256 encoreRewardToDistribute = encoreRewardWhole.sub(encoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(encoreRewardFee);
pool.accEncorePerShare = pool.accEncorePerShare.add(
encoreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
function safeFixUnits(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12);
}
// Deposit tokens to EncoreVault for ENCORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(pool.depositable == true, "Depositing into this pool is disabled");
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.transferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
require(pool.depositable == true, "Depositing into this pool is disabled");
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.transferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
function setENCOREETHLPBurnAddress(address _burn) public onlyOwner {
ENCOREETHLPBurnAddress = _burn;
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from EncoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
function claim(uint256 _pid) public {
_withdraw(_pid, 0, msg.sender,msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][from];
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming ENCORE farmed
if(_amount > 0) {
require(pool.withdrawable, "Withdrawing from this pool is disabled");
user.amount = user.amount.sub(_amount, "Insufficient balance");
if(_pid == 0) {
if(voidWithdrawList[to] || ENCOREETHLPBurnAddress == address(0)) {
pool.token.transfer(address(to), _amount);
} else {
pool.token.transfer(address(to), _amount.mul(95).div(100));
pool.token.transfer(address(ENCOREETHLPBurnAddress), _amount.mul(5).div(100));
}
} else {
pool.token.transfer(address(to), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingENCORE(_pid, from);
if(pending > 0) {
safeEncoreTransfer(from, pending);
}
}
function pendingENCORE(uint256 _pid, address _user) public view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accEncorePerShare = pool.accEncorePerShare;
return user.amount.mul(accEncorePerShare).div(1e12).sub(user.rewardDebt);
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.transfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe encore transfer function, just in case if rounding error causes pool to not have enough ENCOREs.
function safeEncoreTransfer(address _to, uint256 _amount) internal {
if(_amount == 0) return;
uint256 encoreBal = encore.balanceOf(address(this));
encore.transfer(_to, _amount);
encoreBalance = encore.balanceOf(address(this));
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
safeEncoreTransfer(devaddr, devSend);
}
}
function stakedTokens(uint256 _pid, address _user) public view returns (uint256) {
UserInfo storage user = userInfo[_pid][_user];
return user.amount;
}
// Update dev address by the previous dev.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
}
|
Add a new token pool. Can only be called by the owner. Note contract owner is meant to be a governance contract allowing ENCORE governance consensus
|
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable,
bool _depositable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accEncorePerShare: 0,
withdrawable : _withdrawable,
depositable : _depositable
})
);
}
| 299,354 |
//Address: 0xa3e97b1da9c3684324fe38627c40e94555f39b18
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 2/18/2018
//Transacion Count: 12
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title ICO CONTRACT
* @dev ERC-20 Token Standard Complian
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Crowdsale is Ownable {
using SafeMath for uint256;
// The token being sold
token public token_reward;
// start and end timestamps where investments are allowed (both inclusive
uint256 public start_time = now; //for testing
//uint256 public start_time = 1517846400; //02/05/2018 @ 4:00pm (UTC) or 5 PM (UTC + 1)
uint256 public end_Time = 1522454400; // 03/31/2018 @ 12:00am (UTC)
uint256 public phase_1_remaining_tokens = 50000000 * (10 ** uint256(8));
uint256 public phase_2_remaining_tokens = 50000000 * (10 ** uint256(8));
uint256 public phase_3_remaining_tokens = 50000000 * (10 ** uint256(8));
uint256 public phase_4_remaining_tokens = 50000000 * (10 ** uint256(8));
uint256 public phase_5_remaining_tokens = 50000000 * (10 ** uint256(8));
uint256 public phase_1_bonus = 40;
uint256 public phase_2_bonus = 20;
uint256 public phase_3_bonus = 15;
uint256 public phase_4_bonus = 10;
uint256 public phase_5_bonus = 5;
uint256 public token_price = 2;// 2 cents
// address where funds are collected
address public wallet;
// Ether to $ price
uint256 public eth_to_usd = 1000;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// rate change event
event EthToUsdChanged(address indexed owner, uint256 old_eth_to_usd, uint256 new_eth_to_usd);
// constructor
function Crowdsale(address tokenContractAddress) public{
wallet = 0x1aC024482b91fa9AaF22450Ff60680BAd60bF8D3;//wallet where ETH will be transferred
token_reward = token(tokenContractAddress);
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function getRate() constant public returns (uint256){
return eth_to_usd.mul(100).div(token_price);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= start_time && now <= end_Time;
bool allPhaseFinished = phase_5_remaining_tokens > 0;
bool nonZeroPurchase = msg.value != 0;
bool minPurchase = eth_to_usd*msg.value >= 100; // minimum purchase $100
return withinPeriod && nonZeroPurchase && allPhaseFinished && minPurchase;
}
// @return true if the admin can send tokens manually
function validPurchaseForManual() internal constant returns (bool) {
bool withinPeriod = now >= start_time && now <= end_Time;
bool allPhaseFinished = phase_5_remaining_tokens > 0;
return withinPeriod && allPhaseFinished;
}
// check token availibility for current phase and max allowed token balance
function checkAndUpdateTokenForManual(uint256 _tokens) internal returns (bool){
if(phase_1_remaining_tokens > 0){
if(_tokens > phase_1_remaining_tokens){
uint256 tokens_from_phase_2 = _tokens.sub(phase_1_remaining_tokens);
phase_1_remaining_tokens = 0;
phase_2_remaining_tokens = phase_2_remaining_tokens.sub(tokens_from_phase_2);
}else{
phase_1_remaining_tokens = phase_1_remaining_tokens.sub(_tokens);
}
return true;
}else if(phase_2_remaining_tokens > 0){
if(_tokens > phase_2_remaining_tokens){
uint256 tokens_from_phase_3 = _tokens.sub(phase_2_remaining_tokens);
phase_2_remaining_tokens = 0;
phase_3_remaining_tokens = phase_3_remaining_tokens.sub(tokens_from_phase_3);
}else{
phase_2_remaining_tokens = phase_2_remaining_tokens.sub(_tokens);
}
return true;
}else if(phase_3_remaining_tokens > 0){
if(_tokens > phase_3_remaining_tokens){
uint256 tokens_from_phase_4 = _tokens.sub(phase_3_remaining_tokens);
phase_3_remaining_tokens = 0;
phase_4_remaining_tokens = phase_4_remaining_tokens.sub(tokens_from_phase_4);
}else{
phase_3_remaining_tokens = phase_3_remaining_tokens.sub(_tokens);
}
return true;
}else if(phase_4_remaining_tokens > 0){
if(_tokens > phase_4_remaining_tokens){
uint256 tokens_from_phase_5 = _tokens.sub(phase_4_remaining_tokens);
phase_4_remaining_tokens = 0;
phase_5_remaining_tokens = phase_5_remaining_tokens.sub(tokens_from_phase_5);
}else{
phase_4_remaining_tokens = phase_4_remaining_tokens.sub(_tokens);
}
return true;
}else if(phase_5_remaining_tokens > 0){
if(_tokens > phase_5_remaining_tokens){
return false;
}else{
phase_5_remaining_tokens = phase_5_remaining_tokens.sub(_tokens);
}
}else{
return false;
}
}
// function to transfer token manually
function transferManually(uint256 _tokens, address to_address) onlyOwner public returns (bool){
require(to_address != 0x0);
require(validPurchaseForManual());
require(checkAndUpdateTokenForManual(_tokens));
token_reward.transfer(to_address, _tokens);
return true;
}
// check token availibility for current phase and max allowed token balance
function transferIfTokenAvailable(uint256 _tokens, uint256 _weiAmount, address _beneficiary) internal returns (bool){
uint256 total_token_to_transfer = 0;
uint256 bonus = 0;
if(phase_1_remaining_tokens > 0){
if(_tokens > phase_1_remaining_tokens){
uint256 tokens_from_phase_2 = _tokens.sub(phase_1_remaining_tokens);
bonus = (phase_1_remaining_tokens.mul(phase_1_bonus).div(100)).add(tokens_from_phase_2.mul(phase_2_bonus).div(100));
phase_1_remaining_tokens = 0;
phase_2_remaining_tokens = phase_2_remaining_tokens.sub(tokens_from_phase_2);
}else{
phase_1_remaining_tokens = phase_1_remaining_tokens.sub(_tokens);
bonus = _tokens.mul(phase_1_bonus).div(100);
}
total_token_to_transfer = _tokens + bonus;
}else if(phase_2_remaining_tokens > 0){
if(_tokens > phase_2_remaining_tokens){
uint256 tokens_from_phase_3 = _tokens.sub(phase_2_remaining_tokens);
bonus = (phase_2_remaining_tokens.mul(phase_2_bonus).div(100)).add(tokens_from_phase_3.mul(phase_3_bonus).div(100));
phase_2_remaining_tokens = 0;
phase_3_remaining_tokens = phase_3_remaining_tokens.sub(tokens_from_phase_3);
}else{
phase_2_remaining_tokens = phase_2_remaining_tokens.sub(_tokens);
bonus = _tokens.mul(phase_2_bonus).div(100);
}
total_token_to_transfer = _tokens + bonus;
}else if(phase_3_remaining_tokens > 0){
if(_tokens > phase_3_remaining_tokens){
uint256 tokens_from_phase_4 = _tokens.sub(phase_3_remaining_tokens);
bonus = (phase_3_remaining_tokens.mul(phase_3_bonus).div(100)).add(tokens_from_phase_4.mul(phase_4_bonus).div(100));
phase_3_remaining_tokens = 0;
phase_4_remaining_tokens = phase_4_remaining_tokens.sub(tokens_from_phase_4);
}else{
phase_3_remaining_tokens = phase_3_remaining_tokens.sub(_tokens);
bonus = _tokens.mul(phase_3_bonus).div(100);
}
total_token_to_transfer = _tokens + bonus;
}else if(phase_4_remaining_tokens > 0){
if(_tokens > phase_4_remaining_tokens){
uint256 tokens_from_phase_5 = _tokens.sub(phase_4_remaining_tokens);
bonus = (phase_4_remaining_tokens.mul(phase_4_bonus).div(100)).add(tokens_from_phase_5.mul(phase_5_bonus).div(100));
phase_4_remaining_tokens = 0;
phase_5_remaining_tokens = phase_5_remaining_tokens.sub(tokens_from_phase_5);
}else{
phase_4_remaining_tokens = phase_4_remaining_tokens.sub(_tokens);
bonus = _tokens.mul(phase_4_bonus).div(100);
}
total_token_to_transfer = _tokens + bonus;
}else if(phase_5_remaining_tokens > 0){
if(_tokens > phase_5_remaining_tokens){
total_token_to_transfer = 0;
}else{
phase_5_remaining_tokens = phase_5_remaining_tokens.sub(_tokens);
bonus = _tokens.mul(phase_5_bonus).div(100);
total_token_to_transfer = _tokens + bonus;
}
}else{
total_token_to_transfer = 0;
}
if(total_token_to_transfer > 0){
token_reward.transfer(_beneficiary, total_token_to_transfer);
TokenPurchase(msg.sender, _beneficiary, _weiAmount, total_token_to_transfer);
return true;
}else{
return false;
}
}
// fallback function can be used to buy tokens
function () payable public{
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = (weiAmount.mul(getRate())).div(10 ** uint256(10));
// Check is there are enough token available for current phase and per person
require(transferIfTokenAvailable(tokens, weiAmount, beneficiary));
// update state
weiRaised = weiRaised.add(weiAmount);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > end_Time;
}
// function to transfer token back to owner
function transferBack(uint256 tokens, address to_address) onlyOwner public returns (bool){
token_reward.transfer(to_address, tokens);
return true;
}
// function to change rate
function changeEth_to_usd(uint256 _eth_to_usd) onlyOwner public returns (bool){
EthToUsdChanged(msg.sender, eth_to_usd, _eth_to_usd);
eth_to_usd = _eth_to_usd;
return true;
}
}
|
return true if the admin can send tokens manually
|
function validPurchaseForManual() internal constant returns (bool) {
bool withinPeriod = now >= start_time && now <= end_Time;
bool allPhaseFinished = phase_5_remaining_tokens > 0;
return withinPeriod && allPhaseFinished;
}
| 2,501,675 |
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/interfaces/IERC20.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/interfaces/IERC165.sol';
import '@openzeppelin/contracts/interfaces/IERC2981.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol';
contract BillionBuns is ERC721Enumerable, Ownable, Pausable, ReentrancyGuard, IERC2981 {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
uint8 private redeemedGiveaways;
bool public saleActive = false;
string public PROVENANCE_HASH = "";
string private baseURI;
string private tokenSuffixURI;
string private contractMetadata = 'contract.json';
uint256 public constant SALE_PRICE = 88000000000000000; // 0.088 ETH
uint8 public constant MINT_BATCH_LIMIT = 5; // Max number of Tokens minted in a single txn
uint8 public constant RESERVED_GIVEAWAYS = 12; // Tokens reserved for giveaway list
uint256 public saleStartsAt;
uint256 public publicsaleStartsAt;
uint256 public privatesaleStartsAt;
uint256 public privatesaleEndsAt;
uint256 public constant MAX_TOKENS = 876; // Max number of token sold in sale
address[] private recipients;
uint256[] private splits;
uint16 public constant SPLIT_BASE = 10000;
bytes32 public whitelistMerkleRoot;
event TokenMinted(
address indexed owner,
uint256 indexed quantity
);
event SaleStatusChange(
address indexed issuer,
bool indexed status
);
event ContractWithdraw(
address indexed initiator,
uint256 amount
);
event ContractWithdrawToken(
address indexed initiator,
address indexed token,
uint256 amount
);
event ProvenanceHashSet(
address indexed initiator,
string previousHash,
string newHash
);
event WithdrawAddressChanged(
address indexed previousAddress,
address indexed newAddress
);
uint16 internal royalty = 500; // base 10000, 5%
uint16 public constant BASE = 10000;
constructor(
uint256 _saleStartTime,
string memory _baseContractURI,
string memory _tokenSuffixURI,
string memory _provenaceHash,
address[] memory _recipients,
uint16[] memory _splits
) ERC721('Billion Buns', 'BBUN') {
baseURI = _baseContractURI;
tokenSuffixURI = _tokenSuffixURI;
saleStartsAt = _saleStartTime; // Unix Timestamp
privatesaleStartsAt = saleStartsAt; // Start Private Sale,
privatesaleEndsAt = saleStartsAt + 24 hours; // End of Private Sale,
publicsaleStartsAt = saleStartsAt + 24 hours; // Start of Public Sale,
PROVENANCE_HASH = _provenaceHash;
recipients = _recipients;
splits = _splits;
}
function mintGiveawayNFT(address recipient, uint8 numTokens) public onlyOwner {
require((numTokens + redeemedGiveaways) <= RESERVED_GIVEAWAYS, 'All Giveaways Redeemed');
for (uint8 i = 0; i < numTokens; i++) {
_tokenIds.increment();
_safeMint(recipient, _tokenIds.current());
}
redeemedGiveaways = redeemedGiveaways + numTokens;
emit TokenMinted(recipient, numTokens);
}
function setWhitelistMerkleRoot(bytes32 _root) onlyOwner external {
whitelistMerkleRoot = _root;
}
/**
* @dev mints `numTokens` tokens and assigns it to
* `msg.sender` by calling _safeMint function.
*
* Emits a {TokenMinted} event.
* Emits two {TransferSingle} events via ERC721 Contract.
*
* Requirements:
* - `saleActive` must be set to true.
* - Current timestamp must greater than or equal `saleStartsAt`.
* - Current timestamp must within period of private sale `privatesaleStartsAt` - `privatesaleEndsAt`.
* - `msg.sender` is among whitelisted memebrs based on the merkle proof provided
* - Ether amount sent greater or equal the base price multipled by `numTokens`.
* - `numTokens` within limits of max number of tokens minted in single txn.
* - Max number of tokens for the private sale not reahced
* @param numTokens - Number of tokens to be minted
* @param proof -The merkle proof for the whitelisted address
*/
function mintPrivateSale(uint8 numTokens, bytes32[] memory proof) public payable {
require(!Address.isContract(msg.sender), "Cannot mint to a contract");
require(saleActive && block.timestamp >= saleStartsAt, 'Sale not active');
uint256 time = (block.timestamp);
require(time > privatesaleStartsAt && time < privatesaleEndsAt, 'Private sale over');
// bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(proof, whitelistMerkleRoot, keccak256(abi.encodePacked(msg.sender))), 'Restricted Access');
require((_tokenIds.current() + numTokens ) <= MAX_TOKENS + RESERVED_GIVEAWAYS, 'Private sale sold');
require(msg.value >= SALE_PRICE * numTokens, 'Insufficient ETH');
require(numTokens <= MINT_BATCH_LIMIT && numTokens > 0, 'Invalid Num Token');
for (uint256 i = 0; i < numTokens; i++) {
_tokenIds.increment();
_safeMint(msg.sender, _tokenIds.current() );
}
emit TokenMinted(msg.sender, numTokens);
}
/**
* @dev mints `numTokens` tokens and assigns it to
* `msg.sender` by calling _safeMint function.
*
* Emits a {TokenMinted} event.
* Emits two {TransferSingle} events via ERC721 Contract.
*
* Requirements:
* - `saleActive` must be set to true.
* - Current timestamp must greater than or equal `saleStartsAt`.
* - Current timestamp must within period of public sale `publicsaleStartsAt` - `publicsaleEndsAt`.
* - Ether amount sent greater or equal the current price multipled by `numTokens`.
* - `numTokens` within limits of max number of tokens minted in single txn.
* - Max number of tokens for the sale not reahced
* @param numTokens - Number of tokens to be minted
*/
function mintPublicSale(uint8 numTokens) public payable {
require(!Address.isContract(msg.sender), "Sender should be an account address");
require(saleActive && block.timestamp >= publicsaleStartsAt, 'Sale not active');
require(msg.value >= SALE_PRICE * numTokens, 'Insufficient ETH');
require(numTokens <= MINT_BATCH_LIMIT && numTokens > 0, 'Wrong Num Token');
require((_tokenIds.current() + numTokens ) <= MAX_TOKENS + RESERVED_GIVEAWAYS, 'Public sale sold');
for (uint8 i = 0; i < numTokens; i++) {
_tokenIds.increment();
_safeMint(msg.sender, _tokenIds.current() );
}
emit TokenMinted(msg.sender, numTokens);
}
function setBaseURI(string memory baseContractURI) public onlyOwner {
baseURI = baseContractURI;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');
string memory baseContractURI = _baseURI();
return
bytes(baseContractURI).length > 0
? string(abi.encodePacked(baseContractURI, tokenId.toString(), tokenSuffixURI))
: '';
}
/**
* @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 override returns (string memory) {
return baseURI;
}
/**
* @dev returns the base contract metadata json object
* this metadat file is used by OpenSea see {https://docs.opensea.io/docs/contract-level-metadata}
*
*/
function contractURI() public view returns (string memory) {
string memory baseContractURI = _baseURI();
return string(abi.encodePacked(baseContractURI, contractMetadata));
}
/**
* @dev Changes the sale status 'saleActive' from active to not active and vice versa
*
* Only Contract Owner can execute
*
* Emits a {SaleStatusChange} event.
*/
function changeSaleStatus() public onlyOwner {
saleActive = !saleActive;
emit SaleStatusChange(msg.sender, saleActive);
}
/**
* @dev withdraws the contract balance and send it to the withdraw Addresses based on split ratio.
*
* Emits a {ContractWithdraw} event.
*/
function withdraw() public nonReentrant {
uint256 balance = address(this).balance;
for (uint256 i = 0; i < recipients.length; i++) {
(bool sent, ) = payable(recipients[i]).call{value: (balance * splits[i]) / SPLIT_BASE}('');
require(sent, 'Withdraw Failed.');
}
emit ContractWithdraw(msg.sender, balance);
}
/// @notice Calculate the royalty payment
/// @param _salePrice the sale price of the token
function royaltyInfo(uint256, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
return (address(this), (_salePrice * royalty) / BASE);
}
/// @dev set the royalty
/// @param _royalty the royalty in base 10000, 500 = 5%
function setRoyalty(uint16 _royalty) public onlyOwner {
require(_royalty >= 0 && _royalty <= 1000, 'Royalty must be between 0% and 10%.');
royalty = _royalty;
}
/// @dev withdraw ERC20 tokens divided by splits
function withdrawTokens(address _tokenContract) external nonReentrant {
IERC20 tokenContract = IERC20(_tokenContract);
// transfer the token from address of Catbotica address
uint256 balance = tokenContract.balanceOf(address(this));
for (uint256 i = 0; i < recipients.length; i++) {
tokenContract.transfer(recipients[i], (balance * splits[i]) / SPLIT_BASE);
}
emit ContractWithdrawToken(
msg.sender,
_tokenContract,
balance
);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Enumerable, IERC165)
returns (bool)
{
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
function changeWithdrawAddress(address _recipient) external {
require(_recipient != address(0), "Cannot use the zero address.");
require(_recipient != address(this), 'Cannot use the address of this contract.');
require(!Address.isContract(_recipient), "Cannot set recipient to a contract address");
// loop over all the recipients and update the address
bool _found = false;
for (uint256 i = 0; i < recipients.length; i++) {
// if the sender matches one of the recipients, update the address
if (recipients[i] == msg.sender) {
recipients[i] = _recipient;
_found = true;
break;
}
}
require(_found, 'The sender is not a recipient.');
emit WithdrawAddressChanged(msg.sender, _recipient);
}
function getRemSaleSupply() public view returns (uint256) {
return (MAX_TOKENS + RESERVED_GIVEAWAYS - _tokenIds.current());
}
function getTotalSaleSupply() public pure returns (uint256) {
return MAX_TOKENS;
}
/**
* @dev sets `PROVENANCE_HASH`
*
* Only Contract Owner can execute
*
* @param provenanceHash the string for the metadata and images hash
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
emit ProvenanceHashSet(msg.sender,PROVENANCE_HASH,provenanceHash);
PROVENANCE_HASH = provenanceHash;
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
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
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
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) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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);
}
|
mints `numTokens` tokens and assigns it to `msg.sender` by calling _safeMint function. Emits a {TokenMinted} event. Emits two {TransferSingle} events via ERC721 Contract. Requirements: - `saleActive` must be set to true. - Current timestamp must greater than or equal `saleStartsAt`. - Current timestamp must within period of public sale `publicsaleStartsAt` - `publicsaleEndsAt`. - Ether amount sent greater or equal the current price multipled by `numTokens`. - `numTokens` within limits of max number of tokens minted in single txn. - Max number of tokens for the sale not reahced numTokens - Number of tokens to be minted/
|
function mintPublicSale(uint8 numTokens) public payable {
require(!Address.isContract(msg.sender), "Sender should be an account address");
require(saleActive && block.timestamp >= publicsaleStartsAt, 'Sale not active');
require(msg.value >= SALE_PRICE * numTokens, 'Insufficient ETH');
require(numTokens <= MINT_BATCH_LIMIT && numTokens > 0, 'Wrong Num Token');
require((_tokenIds.current() + numTokens ) <= MAX_TOKENS + RESERVED_GIVEAWAYS, 'Public sale sold');
for (uint8 i = 0; i < numTokens; i++) {
_tokenIds.increment();
_safeMint(msg.sender, _tokenIds.current() );
}
emit TokenMinted(msg.sender, numTokens);
}
| 6,200,603 |
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Emitted when `owner` pays to purchase a specific image id.
*/
event Purchase(address indexed owner, string imageId, string name);
/**
* @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;
}
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);
}
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);
}
pragma solidity ^0.8.0;
interface IArtAI is IERC721 {
function tokenIdForName(string memory _paintingName)
external
view
returns (uint256);
function tokenInfo(uint256 _tokenId)
external
view
returns (
string memory _imageHash,
string memory _imageName,
string memory _imageId
);
}
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
);
}
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);
}
}
}
}
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;
}
}
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);
}
}
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;
}
}
pragma solidity ^0.8.0;
contract Ownable {
address _owner;
constructor() {
_owner = msg.sender;
}
modifier onlyOwner() {
require(
msg.sender == _owner,
"Only the contract owner may call this function"
);
_;
}
function owner() public view virtual returns (address) {
return _owner;
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
_owner = newOwner;
}
function withdrawBalance() external onlyOwner {
payable(_owner).transfer(address(this).balance);
}
function withdrawAmountTo(address _recipient, uint256 _amount)
external
onlyOwner
{
require(address(this).balance >= _amount);
payable(_recipient).transfer(_amount);
}
}
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context, Ownable {
/**
* @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;
bool private _allowMinting;
bool private _allowExtending;
/**
* @dev Initializes the contract in paused state.
*/
constructor() {
_paused = true;
_allowMinting = false;
_allowExtending = 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");
_;
}
modifier whenMintingOpen() {
require(!paused() && _allowMinting, "Minting is not open");
_;
}
modifier whenExtendingOpen() {
require(!paused() && _allowExtending, "Extending is not open");
_;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function openExtending() external onlyOwner {
_openExtending();
}
function closeExtending() external onlyOwner {
_closeExtending();
}
function openMinting() external onlyOwner {
_openMinting();
}
function closeMinting() external onlyOwner {
_closeMinting();
}
/**
* @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());
}
function _openMinting() internal virtual whenNotPaused {
_allowMinting = true;
}
function _closeMinting() internal virtual {
_allowMinting = false;
}
function _openExtending() internal virtual whenNotPaused {
_allowExtending = true;
}
function _closeExtending() internal virtual {
_allowExtending = false;
}
}
pragma solidity ^0.8.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 {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature)
internal
pure
returns (address, RecoverError)
{
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(
vs,
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (
uint256(s) >
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n",
Strings.toString(s.length),
s
)
);
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
}
}
pragma solidity ^0.8.0;
contract ArtAI is Context, ERC165, IERC721, IERC721Metadata, Ownable, Pausable {
/**
* @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}.
*/
using Address for address;
using Strings for uint256;
using ECDSA for bytes;
event Burn(
address indexed owner,
uint256 indexed tokenId1,
uint256 indexed tokenId2
);
event Extend(
address owner,
uint256 tokenId,
string oldHash,
string newHash,
string oldName,
string newName,
string oldId,
string newId
);
// Max total supply
uint256 public maxSupply = 5000;
// Max painting name length
uint256 private _maxImageNameLength = 100;
// purchase price
uint256 public _purchasePrice = 50000000000000000 wei;
// public signer address
address private _messageSigner;
// graveyard address
address private _graveyardAddress =
0x000000000000000000000000000000000000dEaD;
// price in burn tokens for a mint
uint256 private _mintCostInBurnTokens = 1;
// Gen 1 Address
address private _gen1Address = 0xaA20f900e24cA7Ed897C44D92012158f436ef791;
// Paintbrush ERC20 address
address private _paintbrushAddress;
// baseURI for Metadata
string private _metadataURI = "https://art-ai.com/api/gen2/metadata/";
// Min Paintbrush balance to extend
uint256 public _minPaintbrushesToExtend;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Token supply
uint256 public _tokenSupply;
// 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;
// Mapping from image name to its purchased status
mapping(string => bool) private _namePurchases;
// Mapping from image name to its token id
mapping(string => uint256) private _nameToTokenId;
// Token Id to image hash
mapping(uint256 => string) private _tokenImageHashes;
// Token Id to image name
mapping(uint256 => string) private _tokenIdToName;
// Token Id to image id
mapping(uint256 => string) private _tokenIdToImageId;
// Status of signed messages
mapping(bytes => bool) private _usedSignedMessages;
// used IPFS hashes
mapping(string => bool) private _usedIPFSHashes;
// used image IDs
mapping(string => bool) private _usedImageIds;
// Burn counts 'tokens' for addresses
mapping(address => uint256) private _burnTokens;
// Gen 1 Available names for address
mapping(address => mapping(string => bool)) private _availableBurnedNames;
// Gen 2 available names for a token id
mapping(uint256 => mapping(string => bool)) private _availableExtendedNames;
/**
* @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_;
}
function isExtensionNameAvailableForToken(
uint256 _tokenId,
string memory _imageName
) external view returns (bool) {
return _availableExtendedNames[_tokenId][_imageName];
}
function isNameAvailableForAddress(
address _address,
string memory _imageName
) external view returns (bool) {
return _availableBurnedNames[_address][_imageName];
}
function setPaintbrushAddress(address newAddress) external onlyOwner {
_paintbrushAddress = newAddress;
}
function setMinPaintbrushesToExtend(uint256 amount) external onlyOwner {
_minPaintbrushesToExtend = amount;
}
function setGen1Address(address newAddress) external onlyOwner {
_gen1Address = newAddress;
}
function tokenIdForName(string memory _paintingName)
external
view
returns (uint256)
{
return _nameToTokenId[_paintingName];
}
function setBaseURI(string memory newURI) external onlyOwner {
_metadataURI = newURI;
}
function setPurchasePrice(uint256 newPrice) external onlyOwner {
_purchasePrice = newPrice;
}
function totalSupply() external view returns (uint256) {
return maxSupply;
}
function setMessageSigner(address newSigner) external onlyOwner {
_messageSigner = newSigner;
}
function burnTokenBalance(address owner) public view returns (uint256) {
return _burnTokens[owner];
}
function lockMinting() external onlyOwner {
maxSupply = _tokenSupply;
_closeMinting();
}
function _burn(uint256 _tokenId1, uint256 _tokenId2) private {
IArtAI(_gen1Address).safeTransferFrom(
msg.sender,
_graveyardAddress,
_tokenId1
);
IArtAI(_gen1Address).safeTransferFrom(
msg.sender,
_graveyardAddress,
_tokenId2
);
(, string memory _name1, ) = IArtAI(_gen1Address).tokenInfo(_tokenId1);
(, string memory _name2, ) = IArtAI(_gen1Address).tokenInfo(_tokenId2);
_availableBurnedNames[msg.sender][_name1] = true;
_availableBurnedNames[msg.sender][_name2] = true;
_burnTokens[msg.sender] += 1;
emit Burn(msg.sender, _tokenId1, _tokenId2);
}
function _verifyName(string memory _imageName) private view returns (bool) {
if (_namePurchases[_imageName]) {
return false;
}
if (IArtAI(_gen1Address).tokenIdForName(_imageName) != 0) {
return _availableBurnedNames[msg.sender][_imageName];
}
return true;
}
function _verifyName(string memory _imageName, uint256 _tokenId)
private
view
returns (bool)
{
if (_availableExtendedNames[_tokenId][_imageName]) {
return true;
}
return _verifyName(_imageName);
}
function _mint(
address _owner,
string memory _imageName,
string memory _imageHash,
string memory _imageId,
bytes memory _signedMessage
) private returns (uint256) {
uint256 _newTokenId = _tokenSupply + 1;
_safeMint(_owner, _newTokenId);
_updateStoredValues(
_imageName,
_imageHash,
_imageId,
_signedMessage,
_newTokenId
);
_burnTokens[msg.sender] -= 1;
return _newTokenId;
}
function _verifySignedMessage(
string memory _imageHash,
string memory _imageId,
string memory _imageName,
bytes memory _signedMessage
) internal returns (bool) {
if (_usedSignedMessages[_signedMessage]) {
return false;
}
bytes32 _message = ECDSA.toEthSignedMessageHash(
abi.encodePacked(_imageId, _imageHash, _imageName)
);
address signer = ECDSA.recover(_message, _signedMessage);
if (signer != _messageSigner) {
return false;
}
_usedSignedMessages[_signedMessage] = true;
return true;
}
function _verifyParams(
string memory _imageName,
string memory _imageHash,
string memory _imageId,
bytes memory _signedMessage
) internal {
require(!_usedImageIds[_imageId], "ImageID");
require(!_usedIPFSHashes[_imageHash], "IPFS hash");
require(bytes(_imageName).length <= _maxImageNameLength, "Name");
require(msg.value >= _purchasePrice, "value");
require(_verifyName(_imageName), "name purchased");
require(
_verifySignedMessage(
_imageHash,
_imageId,
_imageName,
_signedMessage
),
"Signature"
);
}
function _verifyParams(
string memory _imageName,
string memory _imageHash,
string memory _imageId,
bytes memory _signedMessage,
uint256 _tokenId
) internal {
require(!_usedImageIds[_imageId], "ImageID");
require(!_usedIPFSHashes[_imageHash], "IPFS hash");
require(bytes(_imageName).length <= _maxImageNameLength, "Name");
require(msg.value >= _purchasePrice, "value");
require(_verifyName(_imageName, _tokenId), "name purchased");
require(
_verifySignedMessage(
_imageHash,
_imageId,
_imageName,
_signedMessage
),
"Signature"
);
}
function _updateStoredValues(
string memory _imageName,
string memory _imageHash,
string memory _imageId,
bytes memory _signedMessage,
uint256 _tokenId
) private {
_namePurchases[_imageName] = true;
_usedSignedMessages[_signedMessage] = true;
_usedImageIds[_imageId] = true;
_usedIPFSHashes[_imageHash] = true;
_availableExtendedNames[_tokenId][_imageName] = true;
_nameToTokenId[_imageName] = _tokenId;
_tokenImageHashes[_tokenId] = _imageHash;
_tokenIdToName[_tokenId] = _imageName;
_tokenIdToImageId[_tokenId] = _imageId;
}
function _extend(
uint256 _tokenId,
string memory _imageHash,
string memory _imageName,
string memory _imageId,
bytes memory _signedMessage
) private {
string memory oldHash = _tokenImageHashes[_tokenId];
string memory oldName = _tokenIdToName[_tokenId];
string memory oldId = _tokenIdToImageId[_tokenId];
_updateStoredValues(
_imageName,
_imageHash,
_imageId,
_signedMessage,
_tokenId
);
emit Extend(
msg.sender,
_tokenId,
oldHash,
_imageHash,
oldName,
_imageName,
oldId,
_imageId
);
}
function extend(
uint256 _tokenId,
string memory _imageHash,
string memory _imageName,
string memory _imageId,
bytes memory _signedMessage
) external payable whenExtendingOpen {
require(ownerOf(_tokenId) == msg.sender, "Ownership");
require(
IERC721(_gen1Address).balanceOf(msg.sender) > 0 ||
IERC20(_paintbrushAddress).balanceOf(msg.sender) >=
_minPaintbrushesToExtend,
"Balance"
);
_verifyParams(
_imageName,
_imageHash,
_imageId,
_signedMessage,
_tokenId
);
_extend(_tokenId, _imageHash, _imageName, _imageId, _signedMessage);
}
function burn(uint256 _tokenId1, uint256 _tokenId2)
external
whenMintingOpen
{
require(_tokenId1 != _tokenId2, "same tokens");
IERC721 iface = IERC721(_gen1Address);
require(iface.ownerOf(_tokenId1) == msg.sender, "Ownership");
require(iface.ownerOf(_tokenId2) == msg.sender, "Ownership");
require(
iface.isApprovedForAll(msg.sender, address(this)),
"transfer perms"
);
_burn(_tokenId1, _tokenId2);
}
function mint(
string memory _imageHash,
string memory _imageName,
string memory _imageId,
bytes memory _signedMessage
) external payable whenMintingOpen returns (uint256) {
require(_tokenSupply < maxSupply, "Maximum supply");
require(
_burnTokens[msg.sender] >= _mintCostInBurnTokens,
"burn tokens"
);
_verifyParams(_imageName, _imageHash, _imageId, _signedMessage);
uint256 _newTokenId = _mint(
msg.sender,
_imageName,
_imageHash,
_imageId,
_signedMessage
);
return _newTokenId;
}
function tokenInfo(uint256 _tokenId)
external
view
returns (
string memory _imageHash,
string memory _imageName,
string memory _imageId
)
{
return (
_tokenImageHashes[_tokenId],
_tokenIdToName[_tokenId],
_tokenIdToImageId[_tokenId]
);
}
/**
* @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: 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: 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: 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 _metadataURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ArtAI.ownerOf(tokenId);
require(to != owner, "ERC721: 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: 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: 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: 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: 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: nonexistent token");
address owner = ArtAI.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: 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: zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
_tokenSupply += 1;
emit Transfer(address(0), to, 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(ArtAI.ownerOf(tokenId) == from, "ERC721: not own");
require(to != address(0), "ERC721: 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(ArtAI.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: 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 {}
}
|
See {IERC721-safeTransferFrom}./
|
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
| 5,885,101 |
./full_match/5/0xbd9E7EcC34308851285F35ba4388a3281AC7Edab/sources/contracts/extension/LazyMintWithTier.sol
|
Lets an authorized address lazy mint a given amount of NFTs. _amount The number of NFTs to lazy mint. _baseURIForTokens The base URI for the 'n' number of NFTs being lazy minted, where the metadata for each of those NFTs is `${baseURIForTokens}/${tokenId}`. _data Additional bytes data to be used at the discretion of the consumer of the contract. return batchId A unique integer identifier for the batch of NFTs lazy minted together./ Handle tier info.
|
function lazyMint(
uint256 _amount,
string calldata _baseURIForTokens,
string calldata _tier,
bytes calldata _data
) public virtual override returns (uint256 batchId) {
if (!_canLazyMint()) {
revert("Not authorized");
}
if (_amount == 0) {
revert("0 amt");
}
uint256 startId = nextTokenIdToLazyMint;
(nextTokenIdToLazyMint, batchId) = _batchMintMetadata(startId, _amount, _baseURIForTokens);
if (!(tokensInTier[_tier].length > 0)) {
tiers.push(_tier);
}
tokensInTier[_tier].push(TokenRange(startId, batchId));
emit TokensLazyMinted(_tier, startId, startId + _amount - 1, _baseURIForTokens, _data);
return batchId;
}
| 1,952,185 |
//SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
import "./libraries/TransferHelper.sol";
import "./interfaces/external/IWETH9.sol";
import "./interfaces/IUnipilotVault.sol";
import "./interfaces/IUnipilotStrategy.sol";
import "./interfaces/IUnipilotFactory.sol";
import "./libraries/UniswapLiquidityManagement.sol";
import "./libraries/UniswapPoolActions.sol";
import "@openzeppelin/contracts/drafts/ERC20Permit.sol";
/// @title Unipilot Active Vault
/// @author 0xMudassir & 721Orbit
/// @dev Active liquidity managment contract that handles user liquidity of any Uniswap V3 pool & earn fees for them
/// @dev minimalist, and gas-optimized contract that ensures user liquidity is always
/// in range and earns maximum amount of fees available at current liquidity utilization
/// rate.
/// @dev In order to minimize IL for users contract pulls liquidity to the vault (HODL) when necessary
contract UnipilotActiveVault is ERC20Permit, IUnipilotVault {
using LowGasSafeMath for uint256;
using UniswapPoolActions for IUniswapV3Pool;
using UniswapLiquidityManagement for IUniswapV3Pool;
IERC20 private token0;
IERC20 private token1;
uint24 private fee;
int24 private tickSpacing;
TicksData public ticksData;
IUniswapV3Pool private pool;
IUnipilotFactory private unipilotFactory;
address private WETH;
uint32 private _pulled = 1;
uint32 private _unlocked = 1;
uint32 private _initialized = 1;
mapping(address => bool) private _operatorApproved;
modifier onlyGovernance() {
(address governance, , , , ) = getProtocolDetails();
require(msg.sender == governance);
_;
}
modifier onlyOperator() {
require(_operatorApproved[msg.sender]);
_;
}
modifier nonReentrant() {
require(_unlocked == 1);
_unlocked = 2;
_;
_unlocked = 1;
}
modifier checkDeviation() {
(, address strategy, , , ) = getProtocolDetails();
IUnipilotStrategy(strategy).checkDeviation(address(pool));
_;
}
constructor(
address _pool,
address _unipilotFactory,
address _WETH,
address governance,
string memory _name,
string memory _symbol
) ERC20Permit(_name) ERC20(_name, _symbol) {
WETH = _WETH;
unipilotFactory = IUnipilotFactory(_unipilotFactory);
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
fee = pool.fee();
tickSpacing = pool.tickSpacing();
_operatorApproved[governance] = true;
}
receive() external payable {}
fallback() external payable {}
/// @dev sets initial position of the vault & can only called once by the governer
function init() external onlyGovernance {
require(_initialized == 1);
_initialized = 2;
int24 _tickSpacing = tickSpacing;
int24 baseThreshold = _tickSpacing * getBaseThreshold();
(, int24 currentTick, ) = pool.getSqrtRatioX96AndTick();
int24 tickFloor = UniswapLiquidityManagement.floor(
currentTick,
_tickSpacing
);
ticksData.baseTickLower = tickFloor - baseThreshold;
ticksData.baseTickUpper = tickFloor + baseThreshold;
UniswapLiquidityManagement.checkRange(
ticksData.baseTickLower,
ticksData.baseTickUpper
);
}
/// @inheritdoc IUnipilotVault
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
address recipient
)
external
payable
override
nonReentrant
returns (
uint256 lpShares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Desired > 0 && amount1Desired > 0);
address sender = _msgSender();
(lpShares, amount0, amount1) = pool.computeLpShares(
true,
amount0Desired,
amount1Desired,
_balance0(),
_balance1(),
totalSupply(),
ticksData
);
pay(address(token0), sender, address(this), amount0);
pay(address(token1), sender, address(this), amount1);
if (_pulled == 1) {
pool.mintLiquidity(
ticksData.baseTickLower,
ticksData.baseTickUpper,
amount0,
amount1
);
}
if (address(this).balance > 0)
TransferHelper.safeTransferETH(msg.sender, address(this).balance);
_mint(recipient, lpShares);
emit Deposit(sender, recipient, amount0, amount1, lpShares);
}
/// @inheritdoc IUnipilotVault
function withdraw(
uint256 liquidity,
address recipient,
bool refundAsETH
)
external
override
nonReentrant
returns (uint256 amount0, uint256 amount1)
{
require(liquidity > 0);
uint256 totalSupply = totalSupply();
/// @dev if liquidity has pulled in contract then calculate share accordingly
if (_pulled == 1) {
uint256 liquidityShare = FullMath.mulDiv(
liquidity,
1e18,
totalSupply
);
(amount0, amount1) = pool.burnUserLiquidity(
ticksData.baseTickLower,
ticksData.baseTickUpper,
liquidityShare,
address(this)
);
(uint256 fees0, uint256 fees1) = pool.collectPendingFees(
address(this),
ticksData.baseTickLower,
ticksData.baseTickUpper
);
transferFeesToIF(false, fees0, fees1);
}
uint256 unusedAmount0 = FullMath.mulDiv(
_balance0().sub(amount0),
liquidity,
totalSupply
);
uint256 unusedAmount1 = FullMath.mulDiv(
_balance1().sub(amount1),
liquidity,
totalSupply
);
amount0 = amount0.add(unusedAmount0);
amount1 = amount1.add(unusedAmount1);
if (amount0 > 0) {
transferFunds(refundAsETH, recipient, address(token0), amount0);
}
if (amount1 > 0) {
transferFunds(refundAsETH, recipient, address(token1), amount1);
}
_burn(msg.sender, liquidity);
emit Withdraw(recipient, liquidity, amount0, amount1);
if (_pulled == 1) {
(uint256 c0, uint256 c1) = pool.mintLiquidity(
ticksData.baseTickLower,
ticksData.baseTickUpper,
_balance0(),
_balance1()
);
emit CompoundFees(c0, c1);
}
}
/// @inheritdoc IUnipilotVault
function readjustLiquidity() external override onlyOperator checkDeviation {
_pulled = 1;
ReadjustVars memory a;
(uint128 totalLiquidity, , ) = pool.getPositionLiquidity(
ticksData.baseTickLower,
ticksData.baseTickUpper
);
(a.amount0Desired, a.amount1Desired, a.fees0, a.fees1) = pool
.burnLiquidity(
ticksData.baseTickLower,
ticksData.baseTickUpper,
address(this)
);
transferFeesToIF(true, a.fees0, a.fees1);
int24 baseThreshold = tickSpacing * getBaseThreshold();
(, a.currentTick, ) = pool.getSqrtRatioX96AndTick();
(a.tickLower, a.tickUpper) = UniswapLiquidityManagement.getBaseTicks(
a.currentTick,
baseThreshold,
tickSpacing
);
if (
(totalLiquidity > 0) &&
(a.amount0Desired == 0 || a.amount1Desired == 0)
) {
bool zeroForOne = a.amount0Desired > 0 ? true : false;
int256 amountSpecified = zeroForOne
? int256(FullMath.mulDiv(a.amount0Desired, 50, 100))
: int256(FullMath.mulDiv(a.amount1Desired, 50, 100));
pool.swapToken(address(this), zeroForOne, amountSpecified);
} else {
a.amount0Desired = _balance0();
a.amount1Desired = _balance1();
a.liquidity = pool.getLiquidityForAmounts(
a.amount0Desired,
a.amount1Desired,
a.tickLower,
a.tickUpper
);
(a.amount0, a.amount1) = pool.getAmountsForLiquidity(
a.liquidity,
a.tickLower,
a.tickUpper
);
a.zeroForOne = UniswapLiquidityManagement.amountsDirection(
a.amount0Desired,
a.amount1Desired,
a.amount0,
a.amount1
);
a.amountSpecified = a.zeroForOne
? int256(
FullMath.mulDiv(a.amount0Desired.sub(a.amount0), 50, 100)
)
: int256(
FullMath.mulDiv(a.amount1Desired.sub(a.amount1), 50, 100)
);
pool.swapToken(address(this), a.zeroForOne, a.amountSpecified);
}
a.amount0Desired = _balance0();
a.amount1Desired = _balance1();
(ticksData.baseTickLower, ticksData.baseTickUpper) = pool
.getPositionTicks(
a.amount0Desired,
a.amount1Desired,
baseThreshold,
tickSpacing
);
pool.mintLiquidity(
ticksData.baseTickLower,
ticksData.baseTickUpper,
a.amount0Desired,
a.amount1Desired
);
}
/// @notice Updates Unipilot's position.
/// @dev Finds base position and limit position for imbalanced token
/// mints all amounts to this position(including earned fees)
/// @dev Must be called by the current governer or selected operators
function rerange() external onlyOperator {
_pulled = 1;
(, , uint256 fees0, uint256 fees1) = pool.burnLiquidity(
ticksData.baseTickLower,
ticksData.baseTickUpper,
address(this)
);
transferFeesToIF(true, fees0, fees1);
int24 baseThreshold = tickSpacing * getBaseThreshold();
(ticksData.baseTickLower, ticksData.baseTickUpper) = pool
.rerangeLiquidity(
baseThreshold,
tickSpacing,
_balance0(),
_balance1()
);
}
/// @inheritdoc IUnipilotVault
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external override {
_verifyCallback();
address recipient = msg.sender;
address payer = abi.decode(data, (address));
if (amount0Owed > 0)
pay(address(token0), payer, recipient, amount0Owed);
if (amount1Owed > 0)
pay(address(token1), payer, recipient, amount1Owed);
}
/// @inheritdoc IUnipilotVault
function uniswapV3SwapCallback(
int256 amount0,
int256 amount1,
bytes calldata data
) external override {
_verifyCallback();
require(amount0 > 0 || amount1 > 0);
bool zeroForOne = abi.decode(data, (bool));
if (zeroForOne)
pay(address(token0), address(this), msg.sender, uint256(amount0));
else pay(address(token1), address(this), msg.sender, uint256(amount1));
}
/// @dev Burns all the Unipilot position and HODL in the vault to prevent users from huge IL
/// Only called by the governer or selected operators
/// @dev Users can also deposit/withdraw during HODL period.
function pullLiquidity(address recipient) external onlyOperator {
require(unipilotFactory.isWhitelist(recipient));
(
uint256 reserves0,
uint256 reserves1,
uint256 fees0,
uint256 fees1
) = pool.burnLiquidity(
ticksData.baseTickLower,
ticksData.baseTickUpper,
recipient
);
if (recipient != address(this)) {
pay(address(token0), address(this), recipient, _balance0());
pay(address(token1), address(this), recipient, _balance1());
}
_pulled = 2;
emit PullLiquidity(reserves0, reserves1, fees0, fees1);
}
/// @notice Calculates the vault's total holdings of TOKEN0 and TOKEN1 - in
/// other words, how much of each token the vault would hold if it withdrew
/// all its liquidity from Uniswap.
/// @dev Updates the position and return the updated reserves, fees & liquidity.
/// @return amount0 Amount of token0 in the unipilot vault
/// @return amount1 Amount of token1 in the unipilot vault
/// @return fees0 Total amount of fees collected by unipilot position in terms of token0
/// @return fees1 Total amount of fees collected by unipilot position in terms of token1
/// @return baseLiquidity The total liquidity of the base position
/// @return rangeLiquidity The total liquidity of the range position - N/A for active vault
function getPositionDetails()
external
returns (
uint256 amount0,
uint256 amount1,
uint256 fees0,
uint256 fees1,
uint128 baseLiquidity,
uint128 rangeLiquidity
)
{
return pool.getTotalAmounts(true, ticksData);
}
/// @notice Updates the status of given account as operator
/// @dev Must be called by the current governance
/// @param _operator Account to update status
function toggleOperator(address _operator) external onlyGovernance {
_operatorApproved[_operator] = !_operatorApproved[_operator];
}
/// @notice Returns the status for a given operator that can operate readjust & pull liquidity
function isOperator(address _operator) external view returns (bool) {
return _operatorApproved[_operator];
}
/// @notice Returns unipilot vault details
/// @return The first of the two tokens of the pool, sorted by address
/// @return The second of the two tokens of the pool, sorted by address
/// @return The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The address of the Uniswap V3 Pool
function getVaultInfo()
external
view
returns (
address,
address,
uint24,
address
)
{
return (address(token0), address(token1), fee, address(pool));
}
/// @dev Amount of token0 held as unused balance.
function _balance0() internal view returns (uint256) {
return token0.balanceOf(address(this));
}
/// @dev Amount of token1 held as unused balance.
function _balance1() internal view returns (uint256) {
return token1.balanceOf(address(this));
}
/// @notice Verify that caller should be the address of a valid Uniswap V3 Pool
function _verifyCallback() internal view {
require(msg.sender == address(pool));
}
function getBaseThreshold() internal view returns (int24 baseThreshold) {
(, address strategy, , , ) = getProtocolDetails();
return IUnipilotStrategy(strategy).getBaseThreshold(address(pool));
}
function getProtocolDetails()
internal
view
returns (
address governance,
address strategy,
address indexFund,
uint8 indexFundPercentage,
uint8 swapPercentage
)
{
return unipilotFactory.getUnipilotDetails();
}
/// @dev method to transfer unipilot earned fees to Index Fund
function transferFeesToIF(
bool isReadjustLiquidity,
uint256 fees0,
uint256 fees1
) internal {
(, , address indexFund, uint8 percentage, ) = getProtocolDetails();
if (fees0 > 0)
token0.transfer(indexFund, FullMath.mulDiv(fees0, percentage, 100));
if (fees1 > 0)
token1.transfer(indexFund, FullMath.mulDiv(fees1, percentage, 100));
emit FeesSnapshot(isReadjustLiquidity, fees0, fees1);
}
function transferFunds(
bool refundAsETH,
address recipient,
address token,
uint256 amount
) internal {
if (refundAsETH && token == WETH) {
IWETH9(WETH).withdraw(amount);
TransferHelper.safeTransferETH(recipient, amount);
} else {
TransferHelper.safeTransfer(token, recipient, amount);
}
}
/// @param token The token to pay
/// @param payer The entity that must pay
/// @param recipient The entity that will receive payment
/// @param value The amount to pay
function pay(
address token,
address payer,
address recipient,
uint256 value
) internal {
if (token == WETH && address(this).balance >= value) {
// pay with WETH9
IWETH9(WETH).deposit{ value: value }(); // wrap only what is needed to pay
IWETH9(WETH).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
//import "../interfaces/external/IERC20.sol";
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(
IERC20.transferFrom.selector,
from,
to,
value
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"STF"
);
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20.transfer.selector, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"ST"
);
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20.approve.selector, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"SA"
);
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{ value: value }(new bytes(0));
require(success, "STE");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IUnipilotVault {
struct ReadjustVars {
uint256 fees0;
uint256 fees1;
int24 currentTick;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint128 liquidity;
uint256 amount0;
uint256 amount1;
bool zeroForOne;
int256 amountSpecified;
uint160 exactSqrtPriceImpact;
uint160 sqrtPriceLimitX96;
}
struct TicksData {
int24 baseTickLower;
int24 baseTickUpper;
int24 rangeTickLower;
int24 rangeTickUpper;
}
struct Tick {
int24 baseTickLower;
int24 baseTickUpper;
int24 bidTickLower;
int24 bidTickUpper;
int24 rangeTickLower;
int24 rangeTickUpper;
}
struct Cache {
uint256 totalSupply;
uint256 liquidityShare;
}
event Deposit(
address indexed depositor,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 lpShares
);
event FeesSnapshot(bool isReadjustLiquidity, uint256 fees0, uint256 fees1);
event Withdraw(
address indexed recipient,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event PullLiquidity(
uint256 reserves0,
uint256 reserves1,
uint256 fees0,
uint256 fees1
);
event CompoundFees(uint256 amount0, uint256 amount1);
/// @notice Deposits tokens in proportion to the Unipilot's current holdings & mints them
/// `Unipilot`s LP token.
/// @param amount0Desired Max amount of token0 to deposit
/// @param amount1Desired Max amount of token1 to deposit
/// @param recipient Recipient of shares
/// @return lpShares Number of shares minted
/// @return amount0 Amount of token0 deposited in vault
/// @return amount1 Amount of token1 deposited in vault
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
address recipient
)
external
payable
returns (
uint256 lpShares,
uint256 amount0,
uint256 amount1
);
/// @notice Withdraws the desired shares from the vault with accumulated user fees and transfers to recipient.
/// @param recipient Recipient of tokens
/// @param refundAsETH whether to recieve in WETH or ETH (only valid for WETH/ALT pairs)
/// @return amount0 Amount of token0 sent to recipient
/// @return amount1 Amount of token1 sent to recipient
function withdraw(
uint256 liquidity,
address recipient,
bool refundAsETH
) external returns (uint256 amount0, uint256 amount1);
/// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay to the pool for the minted liquidity.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
/// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap.
/// @dev In the implementation you must pay to the pool for swap.
/// @param amount0Delta The amount of token0 due to the pool for the swap
/// @param amount1Delta The amount of token1 due to the pool for the swap
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
/// @notice Burns all position(s), collects any fees accrued and updates Unipilot's position(s)
/// @dev mints all amounts to this position(s) (including earned fees)
/// @dev For active vaults it can be called by the governance or operator,
/// swaps imbalanced token and add all liquidity in base position.
/// @dev For passive vaults it can be called by any user.
/// Two positions are placed - a base position and a limit position. The base
/// position is placed first with as much liquidity as possible. This position
/// should use up all of one token, leaving only the other one. This excess
/// amount is then placed as a single-sided bid or ask position.
function readjustLiquidity() external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.6;
pragma abicoder v2;
interface IUnipilotStrategy {
struct PoolStrategy {
int24 baseThreshold;
int24 rangeThreshold;
int24 maxTwapDeviation;
int24 readjustThreshold;
uint32 twapDuration;
int24 baseMultiplier;
}
event GovernanceUpdated(address oldGovernance, address newGovernance);
event StrategyUpdated(PoolStrategy oldStrategy, PoolStrategy newStrategy);
event MaxTwapDeviationUpdated(int24 oldDeviation, int24 newDeviation);
event BaseTicksUpdated(int24 oldBaseTicks, int24 newBaseTicks);
event RangeTicksUpdated(int24 oldRangeTicks, int24 newRangeTicks);
event TwapDurationUpdated(uint32 oldDuration, uint32 newDuration);
event ReadjustMultiplierUpdated(int24 oldMultiplier, int24 newMultiplier);
function getTicks(address _pool)
external
returns (
int24 baseLower,
int24 baseUpper,
int24 bidLower,
int24 bidUpper,
int24 askLower,
int24 askUpper
);
function getTwap(address _pool) external view returns (int24);
function getStrategy(address _pool)
external
view
returns (PoolStrategy memory strategy);
function getBaseThreshold(address _pool)
external
view
returns (int24 baseThreshold);
function twapDuration() external view returns (uint32);
function maxTwapDeviation() external view returns (int24);
function checkDeviation(address pool) external view;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/// @title The interface for the Unipilot Factory
interface IUnipilotFactory {
/// @notice Emitted when a vault is created
/// @param _tokenA The first token of the pool by address sort order
/// @param _tokenB The second token of the pool by address sort order
/// @param _fee The fee tier for which the vault is created
/// @param _vault The address of the vault that is created
event VaultCreated(
address indexed _tokenA,
address indexed _tokenB,
uint24 _fee,
address indexed _vault
);
/// @notice Emitted when the governance of the factory is changed
/// @param _oldGovernance The governance before the governance was changed
/// @param _newGovernance The governance after the governance was changed
event GovernanceChanged(
address indexed _oldGovernance,
address indexed _newGovernance
);
/// @notice Creates a vault for the given two tokens and fee
/// @param _tokenA The first token of the pool by address sort order
/// @param _tokenB The second token of the pool by address sort order
/// @param _fee The desired fee for the unipilot vault
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the vault already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return _vault The address of the newly created pool
function createVault(
address _tokenA,
address _tokenB,
uint24 _fee,
uint160 _sqrtPriceX96,
string memory _name,
string memory _symbol
) external returns (address _vault);
/// @notice Returns the vault address for a given uniswap v3 pair of tokens and a fee
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return vault The vault address
function vaults(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address vault);
/// @notice Returns the status for a given account that can recieve the vault reserves after pull liquidity
/// @dev by default vault address will be whitelist as a recipient in order to resist IL
/// @dev Only applicable for active vaults
function isWhitelist(address recipient) external view returns (bool);
/// @notice Used to give addresses of governance, strategy, indexFund
/// @return governance address, strategy address, indexFund address
function getUnipilotDetails()
external
view
returns (
address,
address,
address,
uint8,
uint8
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./UniswapPoolActions.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol";
import "@uniswap/v3-periphery/contracts/libraries/PositionKey.sol";
import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import "../interfaces/IUnipilotVault.sol";
/// @title Liquidity and ticks functions
/// @notice Provides functions for computing liquidity and ticks for token amounts and prices
library UniswapLiquidityManagement {
using LowGasSafeMath for uint256;
struct Info {
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0;
uint256 amount1;
uint128 liquidity;
int24 tickLower;
int24 tickUpper;
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
/// @param pool Uniswap V3 pool
/// @param liquidity The liquidity being valued
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return amounts of token0 and token1 that corresponds to liquidity
function getAmountsForLiquidity(
IUniswapV3Pool pool,
uint128 liquidity,
int24 _tickLower,
int24 _tickUpper
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(_tickLower),
TickMath.getSqrtRatioAtTick(_tickUpper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
/// @param pool Uniswap V3 pool
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return The maximum amount of liquidity that can be held amount0 and amount1
function getLiquidityForAmounts(
IUniswapV3Pool pool,
uint256 amount0,
uint256 amount1,
int24 _tickLower,
int24 _tickUpper
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(_tickLower),
TickMath.getSqrtRatioAtTick(_tickUpper),
amount0,
amount1
);
}
/// @dev Amount of liquidity in contract position.
/// @param pool Uniswap V3 pool
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return liquidity stored in position
function getPositionLiquidity(
IUniswapV3Pool pool,
int24 _tickLower,
int24 _tickUpper
)
internal
view
returns (
uint128 liquidity,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
bytes32 positionKey = PositionKey.compute(
address(this),
_tickLower,
_tickUpper
);
(liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
/// @dev Rounds tick down towards negative infinity so that it's a multiple
/// of `tickSpacing`.
function floor(int24 tick, int24 tickSpacing)
internal
pure
returns (int24)
{
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
function getSqrtRatioX96AndTick(IUniswapV3Pool pool)
internal
view
returns (
uint160 _sqrtRatioX96,
int24 _tick,
uint16 observationCardinality
)
{
(_sqrtRatioX96, _tick, , observationCardinality, , , ) = pool.slot0();
}
/// @dev Calc base ticks depending on base threshold and tickspacing
function getBaseTicks(
int24 currentTick,
int24 baseThreshold,
int24 tickSpacing
) internal pure returns (int24 tickLower, int24 tickUpper) {
int24 tickFloor = floor(currentTick, tickSpacing);
tickLower = tickFloor - baseThreshold;
tickUpper = tickFloor + baseThreshold;
}
function collectableAmountsInPosition(
IUniswapV3Pool pool,
int24 _lowerTick,
int24 _upperTick
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
(
uint128 liquidity,
uint128 earnable0,
uint128 earnable1
) = getPositionLiquidity(pool, _lowerTick, _upperTick);
(uint256 burnable0, uint256 burnable1) = UniswapLiquidityManagement
.getAmountsForLiquidity(pool, liquidity, _lowerTick, _upperTick);
return (burnable0, burnable1, earnable0, earnable1);
}
function computeLpShares(
IUniswapV3Pool pool,
bool isWhitelisted,
uint256 amount0Max,
uint256 amount1Max,
uint256 balance0,
uint256 balance1,
uint256 totalSupply,
IUnipilotVault.TicksData memory ticks
)
internal
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
(
uint256 res0,
uint256 res1,
uint256 fees0,
uint256 fees1,
,
) = getTotalAmounts(pool, isWhitelisted, ticks);
uint256 reserve0 = res0.add(fees0).add(balance0);
uint256 reserve1 = res1.add(fees1).add(balance1);
// If total supply > 0, pool can't be empty
assert(totalSupply == 0 || reserve0 != 0 || reserve1 != 0);
(shares, amount0, amount1) = calculateShare(
amount0Max,
amount1Max,
reserve0,
reserve1,
totalSupply
);
}
function getTotalAmounts(
IUniswapV3Pool pool,
bool isWhitelisted,
IUnipilotVault.TicksData memory ticks
)
internal
returns (
uint256 amount0,
uint256 amount1,
uint256 fees0,
uint256 fees1,
uint128 baseLiquidity,
uint128 rangeLiquidity
)
{
(amount0, amount1, fees0, fees1, baseLiquidity) = getReserves(
pool,
ticks.baseTickLower,
ticks.baseTickUpper
);
if (!isWhitelisted) {
(
uint256 range0,
uint256 range1,
uint256 rangeFees0,
uint256 rangeFees1,
uint128 rangeliquidity
) = getReserves(pool, ticks.rangeTickLower, ticks.rangeTickUpper);
amount0 = amount0.add(range0);
amount1 = amount1.add(range1);
fees0 = fees0.add(rangeFees0);
fees1 = fees1.add(rangeFees1);
rangeLiquidity = rangeliquidity;
}
}
function getReserves(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper
)
internal
returns (
uint256 amount0,
uint256 amount1,
uint256 fees0,
uint256 fees1,
uint128 liquidity
)
{
liquidity = UniswapPoolActions.updatePosition(
pool,
tickLower,
tickUpper
);
if (liquidity > 0) {
(amount0, amount1, fees0, fees1) = collectableAmountsInPosition(
pool,
tickLower,
tickUpper
);
}
}
function calculateShare(
uint256 amount0Max,
uint256 amount1Max,
uint256 reserve0,
uint256 reserve1,
uint256 totalSupply
)
internal
pure
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
if (totalSupply == 0) {
// For first deposit, just use the amounts desired
amount0 = amount0Max;
amount1 = amount1Max;
shares = amount0 > amount1 ? amount0 : amount1; // max
} else if (reserve0 == 0) {
amount1 = amount1Max;
shares = FullMath.mulDiv(amount1, totalSupply, reserve1);
} else if (reserve1 == 0) {
amount0 = amount0Max;
shares = FullMath.mulDiv(amount0, totalSupply, reserve0);
} else {
amount0 = FullMath.mulDiv(amount1Max, reserve0, reserve1);
if (amount0 < amount0Max) {
amount1 = amount1Max;
shares = FullMath.mulDiv(amount1, totalSupply, reserve1);
} else {
amount0 = amount0Max;
amount1 = FullMath.mulDiv(amount0, reserve1, reserve0);
shares = FullMath.mulDiv(amount0, totalSupply, reserve0);
}
}
}
/// @dev Gets ticks with proportion equivalent to desired amount
/// @param pool Uniswap V3 pool
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param baseThreshold The range for upper and lower ticks
/// @param tickSpacing The pool tick spacing
/// @return tickLower The lower tick of the range
/// @return tickUpper The upper tick of the range
function getPositionTicks(
IUniswapV3Pool pool,
uint256 amount0Desired,
uint256 amount1Desired,
int24 baseThreshold,
int24 tickSpacing
) internal view returns (int24 tickLower, int24 tickUpper) {
Info memory cache = Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0);
// Get current price and tick from the pool
(uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0();
//Calc base ticks
(cache.tickLower, cache.tickUpper) = getBaseTicks(
currentTick,
baseThreshold,
tickSpacing
);
//Calc amounts of token0 and token1 that can be stored in base range
(cache.amount0, cache.amount1) = getAmountsForTicks(
pool,
cache.amount0Desired,
cache.amount1Desired,
cache.tickLower,
cache.tickUpper
);
// //Liquidity that can be stored in base range
cache.liquidity = getLiquidityForAmounts(
pool,
cache.amount0,
cache.amount1,
cache.tickLower,
cache.tickUpper
);
// //Get imbalanced token
bool zeroGreaterOne = amountsDirection(
cache.amount0Desired,
cache.amount1Desired,
cache.amount0,
cache.amount1
);
//Calc new tick(upper or lower) for imbalanced token
if (zeroGreaterOne) {
uint160 nextSqrtPrice0 = SqrtPriceMath
.getNextSqrtPriceFromAmount0RoundingUp(
sqrtPriceX96,
cache.liquidity,
cache.amount0Desired,
false
);
cache.tickUpper = floor(
TickMath.getTickAtSqrtRatio(nextSqrtPrice0),
tickSpacing
);
} else {
uint160 nextSqrtPrice1 = SqrtPriceMath
.getNextSqrtPriceFromAmount1RoundingDown(
sqrtPriceX96,
cache.liquidity,
cache.amount1Desired,
false
);
cache.tickLower = floor(
TickMath.getTickAtSqrtRatio(nextSqrtPrice1),
tickSpacing
);
}
checkRange(cache.tickLower, cache.tickUpper);
/// floor the tick again because one tick is still not valid tick due to + - baseThreshold
tickLower = floor(cache.tickLower, tickSpacing);
tickUpper = floor(cache.tickUpper, tickSpacing);
}
/// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks
/// @param pool Uniswap V3 pool
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return amount0 amounts of token0 that can be stored in range
/// @return amount1 amounts of token1 that can be stored in range
function getAmountsForTicks(
IUniswapV3Pool pool,
uint256 amount0Desired,
uint256 amount1Desired,
int24 _tickLower,
int24 _tickUpper
) internal view returns (uint256 amount0, uint256 amount1) {
uint128 liquidity = getLiquidityForAmounts(
pool,
amount0Desired,
amount1Desired,
_tickLower,
_tickUpper
);
(amount0, amount1) = getAmountsForLiquidity(
pool,
liquidity,
_tickLower,
_tickUpper
);
}
/// @dev Common checks for valid tick inputs.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
function checkRange(int24 tickLower, int24 tickUpper) internal pure {
require(tickLower < tickUpper, "TLU");
require(tickLower >= TickMath.MIN_TICK, "TLM");
require(tickUpper <= TickMath.MAX_TICK, "TUM");
}
/// @dev Get imbalanced token
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param amount0 Amounts of token0 that can be stored in base range
/// @param amount1 Amounts of token1 that can be stored in base range
/// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced
function amountsDirection(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0,
uint256 amount1
) internal pure returns (bool zeroGreaterOne) {
zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) >
amount1Desired.sub(amount1).mul(amount0Desired)
? true
: false;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./SafeCastExtended.sol";
import "./UniswapLiquidityManagement.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import "@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol";
/// @title Liquidity and ticks functions
/// @notice Provides functions for computing liquidity and ticks for token amounts and prices
library UniswapPoolActions {
using LowGasSafeMath for uint256;
using SafeCastExtended for uint256;
using UniswapLiquidityManagement for IUniswapV3Pool;
function updatePosition(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper
) internal returns (uint128 liquidity) {
(liquidity, , ) = pool.getPositionLiquidity(tickLower, tickUpper);
if (liquidity > 0) {
pool.burn(tickLower, tickUpper, 0);
}
}
function burnLiquidity(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
address recipient
)
internal
returns (
uint256 amount0,
uint256 amount1,
uint256 fees0,
uint256 fees1
)
{
(uint128 liquidity, , ) = pool.getPositionLiquidity(
tickLower,
tickUpper
);
if (liquidity > 0) {
(amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity);
if (amount0 > 0 || amount1 > 0) {
(uint256 collect0, uint256 collect1) = pool.collect(
recipient,
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
(fees0, fees1) = (collect0.sub(amount0), collect1.sub(amount1));
}
}
}
function burnUserLiquidity(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
uint256 userSharePercentage,
address recipient
) internal returns (uint256 amount0, uint256 amount1) {
(uint128 liquidity, , ) = pool.getPositionLiquidity(
tickLower,
tickUpper
);
uint256 liquidityRemoved = FullMath.mulDiv(
uint256(liquidity),
userSharePercentage,
1e18
);
(amount0, amount1) = pool.burn(
tickLower,
tickUpper,
liquidityRemoved.toUint128()
);
if (amount0 > 0 || amount1 > 0) {
(amount0, amount0) = pool.collect(
recipient,
tickLower,
tickUpper,
amount0.toUint128(),
amount1.toUint128()
);
}
}
function mintLiquidity(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
uint256 amount0Desired,
uint256 amount1Desired
) internal returns (uint256 amount0, uint256 amount1) {
uint128 liquidity = pool.getLiquidityForAmounts(
amount0Desired,
amount1Desired,
tickLower,
tickUpper
);
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(address(this))
);
}
}
function swapToken(
IUniswapV3Pool pool,
address recipient,
bool zeroForOne,
int256 amountSpecified
) internal {
(uint160 sqrtPriceX96, , ) = pool.getSqrtRatioX96AndTick();
uint160 exactSqrtPriceImpact = (sqrtPriceX96 * (1e5 / 2)) / 1e6;
uint160 sqrtPriceLimitX96 = zeroForOne
? sqrtPriceX96 - exactSqrtPriceImpact
: sqrtPriceX96 + exactSqrtPriceImpact;
pool.swap(
recipient,
zeroForOne,
amountSpecified,
sqrtPriceLimitX96,
abi.encode(zeroForOne)
);
}
function collectPendingFees(
IUniswapV3Pool pool,
address recipient,
int24 tickLower,
int24 tickUpper
) internal returns (uint256 collect0, uint256 collect1) {
updatePosition(pool, tickLower, tickUpper);
(collect0, collect1) = pool.collect(
recipient,
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
}
function rerangeLiquidity(
IUniswapV3Pool pool,
int24 baseThreshold,
int24 tickSpacing,
uint256 balance0,
uint256 balance1
) internal returns (int24 tickLower, int24 tickUpper) {
(tickLower, tickUpper) = pool.getPositionTicks(
balance0,
balance1,
baseThreshold,
tickSpacing
);
mintLiquidity(pool, tickLower, tickUpper, balance0, balance1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "../token/ERC20/ERC20.sol";
import "./IERC20Permit.sol";
import "../cryptography/ECDSA.sol";
import "../utils/Counters.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping (address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
import './LowGasSafeMath.sol';
import './SafeCast.sol';
import './FullMath.sol';
import './UnsafeMath.sol';
import './FixedPoint96.sol';
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @notice Gets the next sqrt price given a delta of token0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of token0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
uint256 product;
if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1)
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
} else {
uint256 product;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
/// @notice Gets the next sqrt price given a delta of token1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of token1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient =
(
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return uint256(sqrtPX96).add(quotient).toUint160();
} else {
uint256 quotient =
(
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
require(sqrtPX96 > quotient);
// always fits 160 bits
return uint160(sqrtPX96 - quotient);
}
}
/// @notice Gets the next sqrt price given an input amount of token0 or token1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of token0, or token1, is being swapped in
/// @param zeroForOne Whether the amount in is token0 or token1
/// @return sqrtQX96 The price after adding the input amount to token0 or token1
function getNextSqrtPriceFromInput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountIn,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// round to make sure that we don't pass the target price
return
zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of token0 or token1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of token0, or token1, is being swapped out
/// @param zeroForOne Whether the amount out is token0 or token1
/// @return sqrtQX96 The price after removing the output amount of token0 or token1
function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// round to make sure that we pass the target price
return
zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
require(sqrtRatioAX96 > 0);
return
roundUp
? UnsafeMath.divRoundingUp(
FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
sqrtRatioAX96
)
: FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
roundUp
? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
: FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Helper that gets signed token0 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount0) {
return
liquidity < 0
? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
/// @notice Helper that gets signed token1 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount1) {
return
liquidity < 0
? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
library PositionKey {
/// @dev Returns the key of the position in the core library
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 SafeCastExtended {
/**
* @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 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 >= -2**127 && value < 2**127,
"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 >= -2**63 && value < 2**63,
"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 >= -2**31 && value < 2**31,
"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 >= -2**15 && value < 2**15,
"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 >= -2**7 && value < 2**7,
"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) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "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: MIT
pragma solidity ^0.7.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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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;
}
}
|
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 >= -2**15 && value < 2**15,
"SafeCast: value doesn't fit in 16 bits"
);
return int16(value);
}
| 5,781,994 |
// SPDX-License-Identifier: MIT
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.3;
import "./IERC20.sol";
import "./SafeMath.sol";
import "./ABDKMath64x64.sol";
import "./IAssimilator.sol";
import "./IOracle.sol";
contract TrybToUsdAssimilator is IAssimilator {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IOracle private constant oracle = IOracle(0xB09fC5fD3f11Cf9eb5E1C5Dba43114e3C9f477b5);
IERC20 private constant tryb = IERC20(0x2C537E5624e4af88A7ae4060C022609376C8D0EB);
// solhint-disable-next-line
constructor() {}
function getRate() public view override returns (uint256) {
(, int256 price, , , ) = oracle.latestRoundData();
return uint256(price);
}
// takes raw tryb amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) {
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/XSGD-transfer-from-failed");
uint256 _balance = tryb.balanceOf(address(this));
uint256 _rate = getRate();
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// takes raw tryb amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRaw(uint256 _amount) external override returns (int128 amount_) {
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/XSGD-transfer-from-failed");
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// takes a numeraire amount, calculates the raw amount of tryb, transfers it in and returns the corresponding raw amount
function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/XSGD-transfer-from-failed");
}
// takes a numeraire amount, calculates the raw amount of tryb, transfers it in and returns the corresponding raw amount
function intakeNumeraireLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external override returns (uint256 amount_) {
uint256 _xsgdBal = tryb.balanceOf(_addr);
if (_xsgdBal <= 0) return 0;
// 1e6
_xsgdBal = _xsgdBal.mul(1e18).div(_baseWeight);
// 1e6
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e6).div(_xsgdBal);
amount_ = (_amount.mulu(1e6) * 1e6) / _rate;
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
}
// takes a raw amount of tryb and transfers it out, returns numeraire value of the raw amount
function outputRawAndGetBalance(address _dst, uint256 _amount)
external
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
uint256 _xsgdAmount = ((_amount) * _rate) / 1e8;
bool _transferSuccess = tryb.transfer(_dst, _xsgdAmount);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
uint256 _balance = tryb.balanceOf(address(this));
amount_ = _xsgdAmount.divu(1e6);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// takes a raw amount of tryb and transfers it out, returns numeraire value of the raw amount
function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) {
uint256 _rate = getRate();
uint256 _xsgdAmount = (_amount * _rate) / 1e8;
bool _transferSuccess = tryb.transfer(_dst, _xsgdAmount);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
amount_ = _xsgdAmount.divu(1e6);
}
// takes a numeraire value of tryb, figures out the raw amount, transfers raw amount out, and returns raw amount
function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = tryb.transfer(_dst, amount_);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
}
// takes a numeraire amount and returns the raw amount
function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
}
function viewRawAmountLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external view override returns (uint256 amount_) {
uint256 _xsgdBal = tryb.balanceOf(_addr);
if (_xsgdBal <= 0) return 0;
// 1e6
_xsgdBal = _xsgdBal.mul(1e18).div(_baseWeight);
// 1e6
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e6).div(_xsgdBal);
amount_ = (_amount.mulu(1e6) * 1e6) / _rate;
}
// takes a raw amount and returns the numeraire amount
function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) {
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) {
uint256 _rate = getRate();
uint256 _balance = tryb.balanceOf(_addr);
if (_balance <= 0) return ABDKMath64x64.fromUInt(0);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
function viewNumeraireAmountAndBalance(address _addr, uint256 _amount)
external
view
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
uint256 _balance = tryb.balanceOf(_addr);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
// instead of calculating with chainlink's "rate" it'll be determined by the existing
// token ratio
// Mainly to protect LP from losing
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr
) external view override returns (int128 balance_) {
uint256 _xsgdBal = tryb.balanceOf(_addr);
if (_xsgdBal <= 0) return ABDKMath64x64.fromUInt(0);
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e18).div(_xsgdBal.mul(1e18).div(_baseWeight));
balance_ = ((_xsgdBal * _rate) / 1e6).divu(1e18);
}
}
|
views the numeraire value of the current balance of the reserve, in this case tryb instead of calculating with chainlink's "rate" it'll be determined by the existing token ratio Mainly to protect LP from losing Rate is in 1e6
|
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr
) external view override returns (int128 balance_) {
uint256 _xsgdBal = tryb.balanceOf(_addr);
if (_xsgdBal <= 0) return ABDKMath64x64.fromUInt(0);
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
uint256 _rate = _usdcBal.mul(1e18).div(_xsgdBal.mul(1e18).div(_baseWeight));
balance_ = ((_xsgdBal * _rate) / 1e6).divu(1e18);
}
| 1,274,454 |
pragma solidity ^0.5.0;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => bool) private authorizedCallers;
struct Airline {
bool isRegistered;
bool isFunded;
uint256 funds;
uint256 numberOfVotesReceived;
mapping (address => bool) otherAirlineVotes;
}
mapping(address => Airline) private airlines;
uint256 private _numberOfRegisteredAirlines = 0;
uint256 private _numberOfFundedAirlines = 0;
// Flight struct
struct Flight {
string flightName;
uint256 flightDateTime;
address airline;
uint8 statusCode;
uint256 updatedTimestamp;
address[] insuredPassengers;
}
// string mapping to flight
mapping(bytes32 => Flight) private flights;
bytes32[] private currentFlights;
// passenger with multiply flights
struct Passenger {
mapping(bytes32 => bool) passengerOnFlight;
mapping(bytes32 => uint256) insuranceAmountForFlight;
uint256 balance;
}
mapping(address => Passenger) passengers;
// the contract holds balance of insurance
uint256 private _contractBalance = 0 ether;
// so we don't go in the hole
uint256 private _insuranceBalance = 0 ether;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event ContractDeauthorized(address _contractId);
event ContractAuthorized(address _contractId);
event OperationalStatusChanged(bool _state);
constructor(address airline) public payable {
contractOwner = msg.sender;
_contractBalance = _contractBalance.add(msg.value);
_registerAirline (airline, msg.sender, true);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Data: Caller is not contract owner");
_;
}
modifier requireIsCallerAuthorized() {
require(authorizedCallers[msg.sender] || (msg.sender == contractOwner), "Caller is not authorised");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational() public view returns(bool) {
return operational;
}
function getContractOwner() public view returns (address) {
return contractOwner;
}
function isFlightRegistered(bytes32 key) external view returns(bool) {
return flights[key].airline != address(0);
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus ( bool mode ) external requireContractOwner {
require(mode != operational, "Can't set same state more than once");
operational = mode;
emit OperationalStatusChanged(mode);
}
function authorizeCaller(address contractAddress) external requireContractOwner{
require(authorizedCallers[contractAddress] == false, "Address has already be registered");
authorizedCallers[contractAddress] = true;
emit ContractAuthorized(contractAddress);
}
function deauthorizeCaller(address contractAddress) external requireContractOwner {
require(authorizedCallers[contractAddress] == true, "Address is not registered");
delete authorizedCallers[contractAddress];
emit ContractDeauthorized(contractAddress);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function isAirline( address _address) external view returns(bool) {
return airlines[_address].isRegistered;
}
function hasAirlineAlreadyVoted(address _address, address _registeredAirline) external view requireIsOperational requireIsCallerAuthorized returns(bool) {
return airlines[_address].otherAirlineVotes[_registeredAirline];
}
function registerAirline(address _address, address _registeredAirline, bool _isRegistered) external requireIsOperational requireIsCallerAuthorized {
_registerAirline(_address, _registeredAirline, _isRegistered);
}
function _registerAirline(address _address, address _registeredAirline, bool _isRegistered) private {
airlines[_address].otherAirlineVotes[_registeredAirline] = true;
airlines[_address].isRegistered = _isRegistered;
if(airlines[_address].isRegistered) {
_numberOfRegisteredAirlines = _numberOfRegisteredAirlines.add(1);
}
airlines[_address].numberOfVotesReceived = airlines[_address].numberOfVotesReceived.add(1);
}
function isAirlineRegistered(address _airline) public view requireIsOperational returns (bool success) {
return airlines[_airline].isRegistered;
}
function unregisterAirline(address _address) external requireIsOperational {
delete airlines[_address];
}
function getNumberOfRegisteredAirlines() external view requireIsOperational returns(uint256 _count) {
return _numberOfRegisteredAirlines;
}
function getNumberOfFundedAirlines() external view requireIsOperational returns(uint256 _count) {
return _numberOfFundedAirlines;
}
function getNumberOfVotesForAirline(address _address) external view requireIsOperational returns(uint256) {
return airlines[_address].numberOfVotesReceived;
}
function getContractBalance() external view requireIsOperational returns(uint256) {
return _contractBalance;
}
function getInsuranceBalance() external view requireIsOperational returns(uint256) {
return _insuranceBalance;
}
function registerFlight(bytes32 key, address airline, uint256 flightDateTime, string calldata flightName, uint8 statusCode) external requireIsOperational requireIsCallerAuthorized {
flights[key].airline = airline;
flights[key].flightDateTime = flightDateTime;
flights[key].flightName = flightName;
flights[key].statusCode = statusCode;
currentFlights.push(key);
}
function getFlightData(bytes32 key) external view requireIsOperational requireIsCallerAuthorized returns(string memory flightName, uint256 flightDateTime, address airline, uint8 status) {
require(flights[key].airline != address(0));
return (flights[key].flightName, flights[key].flightDateTime, flights[key].airline, flights[key].statusCode);
}
function getCurrentFlights() external view requireIsOperational requireIsCallerAuthorized returns (bytes32[] memory ) {
return currentFlights;
}
function setFlightStatus(bytes32 key, uint8 status) external requireIsOperational requireIsCallerAuthorized{
require(status != flights[key].statusCode, "Status code already set");
flights[key].statusCode = status;
}
function _removeFlightFromCurrentFlights(bytes32 key) private {
uint256 index = 0;
bool foundKey = false;
while(index < currentFlights.length - 1) {
if(currentFlights[index] == key) {
foundKey = true;
}
if(foundKey) {
currentFlights[index] = currentFlights[index + 1];
}
index++;
}
if(foundKey) {
currentFlights.length--;
}
}
function isAirlineFunded(address _airline) public view requireIsOperational returns (bool success) {
return airlines[_airline].isFunded;
}
function fund (address _address, uint256 _fund, uint256 FUNDING_AMOUNT_REQUIRED) public payable requireIsOperational {
airlines[_address].funds = airlines[_address].funds.add(_fund);
if(!airlines[_address].isFunded && airlines[_address].funds >= FUNDING_AMOUNT_REQUIRED) {
airlines[_address].isFunded = true;
_numberOfFundedAirlines = _numberOfFundedAirlines.add(1);
}
_contractBalance = _contractBalance.add(_fund);
}
function purchaseInsurance(address passenger, uint256 insuranceAmount, bytes32 flightKey) external payable requireIsOperational requireIsCallerAuthorized {
require(!passengers[passenger].passengerOnFlight[flightKey], "Passenger already insured");
passengers[passenger].passengerOnFlight[flightKey] = true;
flights[flightKey].insuredPassengers.push(passenger);
passengers[passenger].insuranceAmountForFlight[flightKey] = insuranceAmount.div(2) + insuranceAmount;
_insuranceBalance = _insuranceBalance.add(passengers[passenger].insuranceAmountForFlight[flightKey]);
_contractBalance = _contractBalance.sub(insuranceAmount.div(2));
}
function processPayment(uint256 value) external payable requireIsOperational requireIsCallerAuthorized {
_contractBalance = _contractBalance.add(value);
}
function() external payable {
_contractBalance = _contractBalance.add(msg.value);
}
function processFlightStatus(bytes32 flightKey, bool wasLateAirline) external requireIsOperational requireIsCallerAuthorized {
uint256 passenger;
uint256 payableAmount;
if(wasLateAirline) {
for(passenger = 0; passenger < flights[flightKey].insuredPassengers.length; passenger++) {
if(passengers[flights[flightKey].insuredPassengers[passenger]].passengerOnFlight[flightKey]) {
payableAmount = passengers[flights[flightKey].insuredPassengers[passenger]].insuranceAmountForFlight[flightKey];
passengers[flights[flightKey].insuredPassengers[passenger]].insuranceAmountForFlight[flightKey] = 0;
passengers[flights[flightKey].insuredPassengers[passenger]].balance = passengers[flights[flightKey].insuredPassengers[passenger]].balance.add(payableAmount);
_insuranceBalance = _insuranceBalance.sub(payableAmount);
}
}
flights[flightKey].insuredPassengers.length = 0;
} else {
for(passenger = 0; passenger < flights[flightKey].insuredPassengers.length; passenger++) {
if(passengers[flights[flightKey].insuredPassengers[passenger]].passengerOnFlight[flightKey]) {
payableAmount = passengers[flights[flightKey].insuredPassengers[passenger]].insuranceAmountForFlight[flightKey];
passengers[flights[flightKey].insuredPassengers[passenger]].insuranceAmountForFlight[flightKey] = 0;
_contractBalance = _contractBalance.add(payableAmount);
_insuranceBalance = _insuranceBalance.sub(payableAmount);
}
}
flights[flightKey].insuredPassengers.length = 0;
}
_removeFlightFromCurrentFlights(flightKey);
}
function payoutFunds(address payable payee) external payable requireIsOperational requireIsCallerAuthorized {
require(passengers[payee].balance > 0, "Must have funds to get paid");
uint256 balanceOwed = passengers[payee].balance;
passengers[payee].balance = 0;
payee.transfer(balanceOwed);
}
}
|
/ SMART CONTRACT FUNCTIONS //
|
function isAirline( address _address) external view returns(bool) {
return airlines[_address].isRegistered;
}
| 12,606,149 |
pragma solidity ^0.4.24;
//================================================================================
// Plague Inc. <Grand prize>
// WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!
// This game is easy for you to get rich.
// Please prepare enough ETH.
// If you have HEART DISEASE, PLEASE DON'T PLAY.
// If you are Chinese or American, please don't play. YOU ARE TOO RICH.
//
// Plague Inc. , which is abbreviated as PIC by players.
// is developed by a well-known games company who put a lot of effort into R&D.
// One evening, our producer had a hands-on experience on FOMO3D.
// and he was really annoyed by the "unreasonable" numerical settings in FOMO3D.
// He said: "We can make a better one!"
// So we made a better one. ^v^
//
// # It takes less time for investors to get back their capital, while making more
// profit (51% for investor dividends).
// # Introducers can get a high return of 10% (effective in the long term).
// # A lot of investors suffered losses in FOMO3D Quick, which is solved perfectly
// by Plague Inc.
// # A total of 11 players will share the grand prize, you don’t have to be the
// last one.
// # Better numerical and time setup, no worries about being in trouble.
//
// ©2030 Plague Inc. All Rights Reserved.
// www.plagueinc.io
// Memorial Bittorrent, eDonkey, eMule. Embrace IPFS
// Blockchain will change the world.
//================================================================================
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
contract PlagueEvents {
//infective person
event onInfectiveStage
(
address indexed player,
uint256 indexed rndNo,
uint256 keys,
uint256 eth,
uint256 timeStamp,
address indexed inveter
);
// become leader during second stage
event onDevelopmentStage
(
address indexed player,
uint256 indexed rndNo,
uint256 eth,
uint256 timeStamp,
address indexed inveter
);
// award
event onAward
(
address indexed player,
uint256 indexed rndNo,
uint256 eth,
uint256 timeStamp
);
}
contract Plague is PlagueEvents{
using SafeMath for *;
using KeysCalc for uint256;
struct Round {
uint256 eth; // total eth
uint256 keys; // total keys
uint256 startTime; // start time
uint256 endTime; // end time
uint256 infectiveEndTime; // infective end time
address leader; // leader
address infectLastPlayer; // the player will award 10% eth
address [11] lastInfective; // the lastest 11 infective
address [4] loseInfective; // the lose infective
bool [11] infectiveAward_m; //
uint256 totalInfective; // the count of this round
uint256 inveterAmount; // remain inveter amount of this round
uint256 lastRoundReward; // last round remain eth 10% + eth 4% - inveterAmount + last remain award
uint256 exAward; // development award
}
struct PlayerRound {
uint256 eth; // eth player has added to round
uint256 keys; // keys
uint256 withdraw; // how many eth has been withdraw
uint256 getInveterAmount; // inverter amount
uint256 hasGetAwardAmount; // player has get award amount
}
uint256 public rndNo = 1; // current round number
uint256 public totalEth = 0; // total eth in all round
uint256 constant private rndInfectiveStage_ = 12 hours; // round timer at infective stage 12 hours;
uint256 constant private rndInfectiveReadyTime_ = 30 minutes; // round timer at infective stage ready time
uint256 constant private rndDevelopmentStage_ = 15 minutes; // round timer at development stage 30 minutes;
uint256 constant private rndDevelopmentReadyTime_ = 12 hours; // round timer at development stage ready time 1 hours;
uint256 constant private allKeys_ = 15000000 * (10 ** 18); // all keys count
uint256 constant private allEths_ = 18703123828125000000000; // all eths count
uint256 constant private rndIncreaseTime_ = 3 hours; // increase time 3 hours
uint256 constant private developmentAwardPercent = 1; // 0.1% reduction every 3 hours
mapping (uint256 => Round) public round_m; // (rndNo => Round)
mapping (uint256 => mapping (address => PlayerRound)) public playerRound_m; // (rndNo => addr => PlayerRound)
address public owner; // owner address
address public receiver = address(0); // receive eth address
uint256 public ownerWithdraw = 0; // how many eth has been withdraw by owner
bool public isStartGame = false; // start game flag
constructor()
public
{
owner = msg.sender;
}
/**
* @dev prevents contracts from interacting
*/
modifier onlyHuman()
{
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth)
{
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
/**
* @dev only owner
*/
modifier onlyOwner()
{
require(owner == msg.sender, "only owner can do it");
_;
}
/**
* @dev It must be human beings to call the function.
*/
function isHuman(address _addr) private view returns (bool)
{
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
return _codeLength == 0;
}
/**
* @dev player infect a person at current round
*
*/
function buyKeys(address _inveter) private
{
uint256 _eth = msg.value;
uint256 _now = now;
uint256 _rndNo = rndNo;
uint256 _ethUse = msg.value;
if (_now > round_m[_rndNo].endTime)
{
require(round_m[_rndNo].endTime + rndDevelopmentReadyTime_ < _now, "we should wait some time");
uint256 lastAwardEth = (round_m[_rndNo].eth.mul(14) / 100).sub(round_m[_rndNo].inveterAmount);
if(round_m[_rndNo].totalInfective < round_m[_rndNo].lastInfective.length)
{
uint256 nextPlayersAward = round_m[_rndNo].lastInfective.length.sub(round_m[_rndNo].totalInfective);
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
if(round_m[_rndNo].infectLastPlayer != address(0))
{
lastAwardEth = lastAwardEth.add(nextPlayersAward.mul(_totalAward.mul(3)/100));
}
else
{
lastAwardEth = lastAwardEth.add(nextPlayersAward.mul(_totalAward.mul(4)/100));
}
}
_rndNo = _rndNo.add(1);
rndNo = _rndNo;
round_m[_rndNo].startTime = _now;
round_m[_rndNo].endTime = _now + rndInfectiveStage_;
round_m[_rndNo].totalInfective = 0;
round_m[_rndNo].lastRoundReward = lastAwardEth;
}
// infective or second stage
if (round_m[_rndNo].keys < allKeys_)
{
// infection stage
uint256 _keys = (round_m[_rndNo].eth).keysRec(_eth);
if (_keys.add(round_m[_rndNo].keys) >= allKeys_)
{
_keys = allKeys_.sub(round_m[_rndNo].keys);
if (round_m[_rndNo].eth >= allEths_)
{
_ethUse = 0;
}
else {
_ethUse = (allEths_).sub(round_m[_rndNo].eth);
}
if (_eth > _ethUse)
{
// refund
msg.sender.transfer(_eth.sub(_ethUse));
}
else {
// fix
_ethUse = _eth;
}
// first stage is over, record current time
round_m[_rndNo].infectiveEndTime = _now.add(rndInfectiveReadyTime_);
round_m[_rndNo].endTime = _now.add(rndDevelopmentStage_).add(rndInfectiveReadyTime_);
round_m[_rndNo].infectLastPlayer = msg.sender;
}
else
{
require (_keys >= 1 * 10 ** 19, "at least 10 thound people");
round_m[_rndNo].endTime = _now + rndInfectiveStage_;
}
round_m[_rndNo].leader = msg.sender;
// update playerRound
playerRound_m[_rndNo][msg.sender].keys = _keys.add(playerRound_m[_rndNo][msg.sender].keys);
playerRound_m[_rndNo][msg.sender].eth = _ethUse.add(playerRound_m[_rndNo][msg.sender].eth);
// update round
round_m[_rndNo].keys = _keys.add(round_m[_rndNo].keys);
round_m[_rndNo].eth = _ethUse.add(round_m[_rndNo].eth);
// update global variable
totalEth = _ethUse.add(totalEth);
// event
emit PlagueEvents.onInfectiveStage
(
msg.sender,
_rndNo,
_keys,
_ethUse,
_now,
_inveter
);
} else {
// second stage
require(round_m[_rndNo].infectiveEndTime < _now, "The virus is being prepared...");
// increase 0.05 Ether every 3 hours
_ethUse = (((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(5 * 10 ** 16)).add((5 * 10 ** 16));
require(_eth >= _ethUse, "Ether amount is wrong");
if(_eth > _ethUse)
{
msg.sender.transfer(_eth.sub(_ethUse));
}
round_m[_rndNo].endTime = _now + rndDevelopmentStage_;
round_m[_rndNo].leader = msg.sender;
// update playerRound
playerRound_m[_rndNo][msg.sender].eth = _ethUse.add(playerRound_m[_rndNo][msg.sender].eth);
// update round
round_m[_rndNo].eth = _ethUse.add(round_m[_rndNo].eth);
// update global variable
totalEth = _ethUse.add(totalEth);
// update development award
uint256 _exAwardPercent = ((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(developmentAwardPercent).add(developmentAwardPercent);
if(_exAwardPercent >= 410)
{
_exAwardPercent = 410;
}
round_m[_rndNo].exAward = (_exAwardPercent.mul(_ethUse) / 1000).add(round_m[_rndNo].exAward);
// event
emit PlagueEvents.onDevelopmentStage
(
msg.sender,
_rndNo,
_ethUse,
_now,
_inveter
);
}
// caculate share inveter amount
if(_inveter != address(0) && isHuman(_inveter))
{
playerRound_m[_rndNo][_inveter].getInveterAmount = playerRound_m[_rndNo][_inveter].getInveterAmount.add(_ethUse.mul(10) / 100);
round_m[_rndNo].inveterAmount = round_m[_rndNo].inveterAmount.add(_ethUse.mul(10) / 100);
}
round_m[_rndNo].loseInfective[round_m[_rndNo].totalInfective % 4] = round_m[_rndNo].lastInfective[round_m[_rndNo].totalInfective % 11];
round_m[_rndNo].lastInfective[round_m[_rndNo].totalInfective % 11] = msg.sender;
round_m[_rndNo].totalInfective = round_m[_rndNo].totalInfective.add(1);
}
/**
* @dev recommend a player
*/
function buyKeyByAddr(address _inveter)
onlyHuman()
isWithinLimits(msg.value)
public
payable
{
require(isStartGame == true, "The game hasn't started yet.");
buyKeys(_inveter);
}
/**
* @dev play
*/
function()
onlyHuman()
isWithinLimits(msg.value)
public
payable
{
require(isStartGame == true, "The game hasn't started yet.");
buyKeys(address(0));
}
/**
* @dev Award by rndNo.
* 0x80ec35ff
* 0x80ec35ff0000000000000000000000000000000000000000000000000000000000000001
*/
function awardByRndNo(uint256 _rndNo)
onlyHuman()
public
{
require(isStartGame == true, "The game hasn't started yet.");
require(_rndNo <= rndNo, "You're running too fast");
uint256 _ethOut = 0;
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
_totalAward = _totalAward.add(round_m[_rndNo].exAward);
uint256 _getAward = 0;
//withdraw award
uint256 _totalWithdraw = round_m[_rndNo].eth.mul(51) / 100;
_totalWithdraw = _totalWithdraw.sub(round_m[_rndNo].exAward);
_totalWithdraw = (_totalWithdraw.mul(playerRound_m[_rndNo][msg.sender].keys));
_totalWithdraw = _totalWithdraw / round_m[_rndNo].keys;
uint256 _inveterAmount = playerRound_m[_rndNo][msg.sender].getInveterAmount;
_totalWithdraw = _totalWithdraw.add(_inveterAmount);
uint256 _withdrawed = playerRound_m[_rndNo][msg.sender].withdraw;
if(_totalWithdraw > _withdrawed)
{
_ethOut = _ethOut.add(_totalWithdraw.sub(_withdrawed));
playerRound_m[_rndNo][msg.sender].withdraw = _totalWithdraw;
}
//lastest infect player
if(msg.sender == round_m[_rndNo].infectLastPlayer && round_m[_rndNo].infectLastPlayer != address(0) && round_m[_rndNo].infectiveEndTime != 0)
{
_getAward = _getAward.add(_totalAward.mul(10)/100);
}
if(now > round_m[_rndNo].endTime)
{
// finally award
if(round_m[_rndNo].leader == msg.sender)
{
_getAward = _getAward.add(_totalAward.mul(60)/100);
}
//finally ten person award
for(uint256 i = 0;i < round_m[_rndNo].lastInfective.length; i = i.add(1))
{
if(round_m[_rndNo].lastInfective[i] == msg.sender && (round_m[_rndNo].totalInfective.sub(1) % 11) != i){
if(round_m[_rndNo].infectiveAward_m[i])
continue;
if(round_m[_rndNo].infectLastPlayer != address(0))
{
_getAward = _getAward.add(_totalAward.mul(3)/100);
}
else{
_getAward = _getAward.add(_totalAward.mul(4)/100);
}
round_m[_rndNo].infectiveAward_m[i] = true;
}
}
}
_ethOut = _ethOut.add(_getAward.sub(playerRound_m[_rndNo][msg.sender].hasGetAwardAmount));
playerRound_m[_rndNo][msg.sender].hasGetAwardAmount = _getAward;
if(_ethOut != 0)
{
msg.sender.transfer(_ethOut);
}
// event
emit PlagueEvents.onAward
(
msg.sender,
_rndNo,
_ethOut,
now
);
}
/**
* @dev Get player bonus data
* 0xd982466d
* 0xd982466d0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000028f211f6c07d3b79e0aab886d56333e4027d4f59
* @return player's award
* @return player's can withdraw amount
* @return player's inveter amount
* @return player's has been withdraw
*/
function getPlayerAwardByRndNo(uint256 _rndNo, address _playAddr)
view
public
returns (uint256, uint256, uint256, uint256)
{
uint256 _ethPlayerAward = 0;
//withdraw award
uint256 _totalWithdraw = round_m[_rndNo].eth.mul(51) / 100;
_totalWithdraw = _totalWithdraw.sub(round_m[_rndNo].exAward);
_totalWithdraw = (_totalWithdraw.mul(playerRound_m[_rndNo][_playAddr].keys));
_totalWithdraw = _totalWithdraw / round_m[_rndNo].keys;
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
_totalAward = _totalAward.add(round_m[_rndNo].exAward);
//lastest infect player
if(_playAddr == round_m[_rndNo].infectLastPlayer && round_m[_rndNo].infectLastPlayer != address(0) && round_m[_rndNo].infectiveEndTime != 0)
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(10)/100);
}
if(now > round_m[_rndNo].endTime)
{
// finally award
if(round_m[_rndNo].leader == _playAddr)
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(60)/100);
}
//finally ten person award
for(uint256 i = 0;i < round_m[_rndNo].lastInfective.length; i = i.add(1))
{
if(round_m[_rndNo].lastInfective[i] == _playAddr && (round_m[_rndNo].totalInfective.sub(1) % 11) != i)
{
if(round_m[_rndNo].infectLastPlayer != address(0))
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(3)/100);
}
else{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(4)/100);
}
}
}
}
return
(
_ethPlayerAward,
_totalWithdraw,
playerRound_m[_rndNo][_playAddr].getInveterAmount,
playerRound_m[_rndNo][_playAddr].hasGetAwardAmount + playerRound_m[_rndNo][_playAddr].withdraw
);
}
/**
* @dev fee withdraw to receiver, everyone can do it.
* 0x6561e6ba
*/
function feeWithdraw()
onlyHuman()
public
{
require(isStartGame == true, "The game hasn't started yet.");
require(receiver != address(0), "The receiver address has not been initialized.");
uint256 _total = (totalEth.mul(5) / (100));
uint256 _withdrawed = ownerWithdraw;
require(_total > _withdrawed, "No need to withdraw");
ownerWithdraw = _total;
receiver.transfer(_total.sub(_withdrawed));
}
/**
* @dev start game
* 0xd65ab5f2
*/
function startGame()
onlyOwner()
public
{
require(isStartGame == false, "The game has already started!");
round_m[1].startTime = now;
round_m[1].endTime = now + rndInfectiveStage_;
round_m[1].lastRoundReward = 0;
isStartGame = true;
}
/**
* @dev change owner.
* 0x547e3f06000000000000000000000000695c7a3c1a27de4bb32cd812a8c2677e25f0b9d5
*/
function changeReceiver(address newReceiver)
onlyOwner()
public
{
receiver = newReceiver;
}
/**
* @dev returns all current round info needed for front end
* 0x747dff42
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256[2], uint256[3], address[2], uint256[6], address[11], address[4])
{
uint256 _rndNo = rndNo;
uint256 _totalAwardAtRound = round_m[_rndNo].lastRoundReward.add(round_m[_rndNo].exAward).add(round_m[_rndNo].eth.mul(30) / 100);
return (
_rndNo,
[round_m[_rndNo].eth, round_m[_rndNo].keys],
[round_m[_rndNo].startTime, round_m[_rndNo].endTime, round_m[_rndNo].infectiveEndTime],
[round_m[_rndNo].leader, round_m[_rndNo].infectLastPlayer],
[getBuyPrice(), round_m[_rndNo].lastRoundReward, _totalAwardAtRound, round_m[_rndNo].inveterAmount, round_m[_rndNo].totalInfective % 11, round_m[_rndNo].exAward],
round_m[_rndNo].lastInfective,
round_m[_rndNo].loseInfective
);
}
/**
* @dev return the price buyer will pay for next 1 individual key during first stage.
* 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rndNo = rndNo;
uint256 _now = now;
// start next round?
if (_now > round_m[_rndNo].endTime)
{
return (750007031250000);
}
if (round_m[_rndNo].keys < allKeys_)
{
return ((round_m[_rndNo].keys.add(10000000000000000000)).ethRec(10000000000000000000));
}
if(round_m[_rndNo].keys >= allKeys_ &&
round_m[_rndNo].infectiveEndTime != 0 &&
round_m[_rndNo].infectLastPlayer != address(0) &&
_now < round_m[_rndNo].infectiveEndTime)
{
return 5 * 10 ** 16;
}
if(round_m[_rndNo].keys >= allKeys_ && _now > round_m[_rndNo].infectiveEndTime)
{
// increase 0.05 Ether every 3 hours
uint256 currentPrice = (((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(5 * 10 ** 16)).add((5 * 10 ** 16));
return currentPrice;
}
//second stage
return (0);
}
}
library KeysCalc {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
|
start game 0xd65ab5f2/
|
function startGame()
onlyOwner()
public
{
require(isStartGame == false, "The game has already started!");
round_m[1].startTime = now;
round_m[1].endTime = now + rndInfectiveStage_;
round_m[1].lastRoundReward = 0;
isStartGame = true;
}
| 1,261,355 |
/**
*Submitted for verification at Etherscan.io on 2020-08-14
*/
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;
}
}
interface ERC20 {
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns(bool);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ethrim is ERC20 {
using SafeMath for uint256;
address public owner;
//1 token = 0.01 eth
uint256 public tokenCost = 0.01 ether;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply = 1e9* 10**18;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
constructor () public {
symbol = "ETRM";
name = "Ethrim";
decimals = 18;
owner = msg.sender;
balances[owner] = totalSupply;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner");
_;
}
/**
* @dev To change burnt Address
* @param _newOwner New owner address
*/
function changeOwner(address _newOwner) public onlyOwner returns(bool) {
require(_newOwner != address(0), "Invalid Address");
owner = _newOwner;
uint256 _value = balances[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_newOwner] = balances[_newOwner].add(_value);
//minting total supply tokens
return true;
}
function getAmountOfToken(uint256 amount) public view returns (uint256) {
uint256 tokenValue = (amount.mul(10 ** 18)).div(tokenCost);
return tokenValue;
}
/**
* @dev Check balance of the holder
* @param _owner Token holder address
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Transfer token to specified address
* @param _to Receiver address
* @param _value Amount of the tokens
*/
function transfer(address _to, uint256 _value) public override returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from The holder address
* @param _to The Receiver address
* @param _value the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool){
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve respective tokens for spender
* @param _spender Spender address
* @param _value Amount of tokens to be allowed
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev To view approved balance
* @param _owner Holder address
* @param _spender Spender address
*/
function allowance(address _owner, address _spender) public override view returns (uint256) {
return allowed[_owner][_spender];
}
function mint(uint256 _tokens) public returns (bool) {
balances[owner] = balances[owner].add(_tokens);
totalSupply = totalSupply.add(_tokens);
return true;
}
}
contract Referral {
using SafeMath for uint256;
//user structure
struct UserStruct {
bool isExist;
//unique id
uint256 id;
//person who referred unique id
uint256 referrerID;
//user current level
uint256 currentLevel;
//total eraning for user
uint256 totalEarningEth;
//persons referred
address[] referral;
//time for every level
uint256 levelExpiresAt;
}
//address to tarnsfer eth/2
address payable public ownerAddress1;
//address to tarnsfer eth/2
address payable public ownerAddress2;
//unique id for every user
uint256 public last_uid = 0;
//token variable
Ethrim public ETRM;
//map user by their unique trust wallet address
mapping(address => UserStruct) public users;
//users trust wallet address corresponding to unique id
mapping(uint256 => address) public userAddresses;
/**
* @dev View referrals
*/
function viewUserReferral(address _userAddress) external view returns (address[] memory) {
return users[_userAddress].referral;
}
}
contract ProjectEthrim {
using SafeMath for uint256;
//user structure
struct UserStruct {
bool isExist;
//unique id
uint256 id;
//person who referred unique id
uint256 referrerID;
//user current level
uint256 currentLevel;
//total eraning for user
uint256 totalEarningEth;
//persons referred
address[] referral;
//time for every level
uint256 levelExpiresAt;
}
//levelInecntives
struct incentiveStruct {
uint256 directNumerator;
uint256 inDirectNumerator;
}
//owner who deploys contracts
address public owner;
//address to tarnsfer eth/2
address payable public ownerAddress1;
//address to tarnsfer eth/2
address payable public ownerAddress2;
//unique id for every user
uint256 public last_uid;
//time limit for each level
uint256 public PERIOD_LENGTH = 60 days;
//no of users in each level
uint256 REFERRALS_LIMIT = 5;
//maximum level from 0 to 7
uint256 MAX_LEVEL = 7;
//precenateg denominator- 100= 10000
uint256 public percentageDenominator = 10000;
//token per level i.e, for L1-> 1*25, L2-> 2*25
uint256 tokenPerLevel = 25;
//token variable
Ethrim public ETRM;
//Referral contract address
Referral public OldEthrimObj;
//map user by their unique trust wallet address
mapping(address => UserStruct) public users;
//users trust wallet address corresponding to unique id
mapping(uint256 => address) public userAddresses;
//maps level incentive by level
mapping(uint256 => incentiveStruct) public LEVEL_INCENTIVE;
//check if user not registered previously
modifier userRegistered() {
require(users[msg.sender].isExist == true, "User is not registered");
_;
}
//check if referrer id is invalid or not
modifier validReferrerID(uint256 _referrerID) {
require( _referrerID > 0 && _referrerID <= last_uid, "Invalid referrer ID");
_;
}
//check if user is already registerd
modifier userNotRegistered() {
require(users[msg.sender].isExist == false, "User is already registered");
_;
}
//check if selected level is valid or not
modifier validLevel(uint256 _level) {
require(_level > 0 && _level <= MAX_LEVEL, "Invalid level entered");
_;
}
event RegisterUserEvent(address indexed user, address indexed referrer, uint256 time);
event BuyLevelEvent(address indexed user, uint256 indexed level, uint256 time);
constructor(address payable _ownerAddress1, address payable _ownerAddress2, address _tokenAddr, address payable _oldEthrimAddr) public {
require(_ownerAddress1 != address(0), "Invalid owner address 1");
require(_ownerAddress2 != address(0), "Invalid owner address 2");
require(_tokenAddr != address(0), "Invalid token address");
owner = msg.sender;
ownerAddress1 = _ownerAddress1;
ownerAddress2 = _ownerAddress2;
ETRM = Ethrim(_tokenAddr);
OldEthrimObj = Referral(_oldEthrimAddr);
OldEthrimObj = Referral(_oldEthrimAddr);
last_uid = OldEthrimObj.last_uid();
//20% = 2000
LEVEL_INCENTIVE[1].directNumerator = 2000;
//10% =1000
LEVEL_INCENTIVE[1].inDirectNumerator = 1000;
//10% = 1000
LEVEL_INCENTIVE[2].directNumerator = 1000;
//5% = 500
LEVEL_INCENTIVE[2].inDirectNumerator = 500;
//6.67% = 667
LEVEL_INCENTIVE[3].directNumerator = 667;
//3.34% = 334
LEVEL_INCENTIVE[3].inDirectNumerator = 334;
//5% = 500
LEVEL_INCENTIVE[4].directNumerator = 500;
//2.5% = 1000
LEVEL_INCENTIVE[4].inDirectNumerator = 250;
//4% = 400
LEVEL_INCENTIVE[5].directNumerator = 400;
//2% = 200
LEVEL_INCENTIVE[5].inDirectNumerator = 200;
//3.34% = 334
LEVEL_INCENTIVE[6].directNumerator = 334;
//1.7% = 170
LEVEL_INCENTIVE[6].inDirectNumerator = 170;
//2.86% = 286
LEVEL_INCENTIVE[7].directNumerator = 286;
//1.43% = 143
LEVEL_INCENTIVE[7].inDirectNumerator = 143;
}
/**
* @dev User registration
*/
function registerUser(uint256 _referrerUniqueID) public payable userNotRegistered() validReferrerID(_referrerUniqueID) {
require(msg.value > 0, "ether value is 0");
uint256 referrerUniqueID = _referrerUniqueID;
if (users[userAddresses[referrerUniqueID]].referral.length >= REFERRALS_LIMIT) {
referrerUniqueID = users[findFreeReferrer(userAddresses[referrerUniqueID])].id;
}
last_uid = last_uid + 1;
users[msg.sender] = UserStruct({
isExist: true,
id: last_uid,
referrerID: referrerUniqueID,
currentLevel: 1,
totalEarningEth: 0,
referral: new address[](0),
levelExpiresAt: now.add(PERIOD_LENGTH)
});
userAddresses[last_uid] = msg.sender;
users[userAddresses[referrerUniqueID]].referral.push(msg.sender);
uint256 tokenAmount = getTokenAmountByLevel(1);
require(ETRM.transferFrom(owner, msg.sender, tokenAmount), "token transfer failed");
//get upline level
address userUpline = userAddresses[referrerUniqueID];
//transfer payment to all upline from current upline
transferLevelPayment(userUpline, 1);
emit RegisterUserEvent(msg.sender, userAddresses[referrerUniqueID], now);
}
/**
* @dev View free Referrer Address
*/
function findFreeReferrer(address _userAddress) public view returns (address) {
if (users[_userAddress].referral.length < REFERRALS_LIMIT){
return _userAddress;
}
address[] memory referrals = new address[](254);
referrals[0] = users[_userAddress].referral[0];
referrals[1] = users[_userAddress].referral[1];
referrals[2] = users[_userAddress].referral[2];
referrals[3] = users[_userAddress].referral[3];
referrals[4] = users[_userAddress].referral[4];
address referrer;
for (uint256 i = 0; i < 1048576; i++) {
if (users[referrals[i]].referral.length < REFERRALS_LIMIT) {
referrer = referrals[i];
break;
}
if (i >= 8191) {
continue;
}
//adding pyramid trees
referrals[((i.add(1).mul(5))).add(i.add(0))] = users[referrals[i]].referral[0];
referrals[((i.add(1).mul(5))).add(i.add(1))] = users[referrals[i]].referral[1];
referrals[((i.add(1).mul(5))).add(i.add(2))] = users[referrals[i]].referral[2];
referrals[((i.add(1).mul(5))).add(i.add(3))] = users[referrals[i]].referral[3];
referrals[((i.add(1).mul(5))).add(i.add(4))] = users[referrals[i]].referral[4];
}
require(referrer != address(0), 'Referrer not found');
return referrer;
}
function transferLevelPayment(address _userUpline, uint256 _levelForIncentive) internal {
//ether value
uint256 etherValue = msg.value;
address uplineAddress = _userUpline;
//current upline to be sent money
uint256 uplineLevel = users[uplineAddress].currentLevel;
//upline user level expiry time
uint256 uplineUserLevelExpiry = users[uplineAddress].levelExpiresAt;
//uid
uint256 uplineUID = users[uplineAddress].id;
//incentive amount total
uint256 amountSentAsIncetives = 0;
uint256 count = 1;
while(uplineUID > 0 && count <= 7) {
address payable receiver = payable(uplineAddress);
if(count == 1) {
uint256 uplineIncentive = (etherValue.mul(LEVEL_INCENTIVE[_levelForIncentive].directNumerator)).div(percentageDenominator);
if(now <= uplineUserLevelExpiry && users[uplineAddress].isExist) {
receiver.transfer(uplineIncentive);
users[uplineAddress].totalEarningEth = users[uplineAddress].totalEarningEth.add(uplineIncentive);
} else {
users[uplineAddress].isExist = false;
(ownerAddress1).transfer(uplineIncentive.div(2));
(ownerAddress2).transfer(uplineIncentive.div(2));
}
amountSentAsIncetives = amountSentAsIncetives.add(uplineIncentive);
} else {
uint256 uplineIncentive = (etherValue.mul(LEVEL_INCENTIVE[_levelForIncentive].inDirectNumerator)).div(percentageDenominator);
if(now <= uplineUserLevelExpiry && users[uplineAddress].isExist) {
receiver.transfer(uplineIncentive);
users[uplineAddress].totalEarningEth = users[uplineAddress].totalEarningEth.add(uplineIncentive);
} else {
users[uplineAddress].isExist = false;
(ownerAddress1).transfer(uplineIncentive.div(2));
(ownerAddress2).transfer(uplineIncentive.div(2));
}
amountSentAsIncetives = amountSentAsIncetives.add(uplineIncentive);
}
//get upline level
uint256 uplineReferrerId = users[uplineAddress].referrerID;
uplineAddress = userAddresses[uplineReferrerId];
//level of upline for user
uplineLevel = users[uplineAddress].currentLevel;
uplineUID = users[uplineAddress].id;
count++;
}
uint256 remAmount = msg.value.sub(amountSentAsIncetives);
transferToOwner(remAmount);
}
function buyLevel(uint256 _level) public payable userRegistered() validLevel(_level){
require(msg.value > 0, "ether value is 0");
uint256 userCurrentLevel = users[msg.sender].currentLevel;
require((_level == userCurrentLevel.add(1)) || (userCurrentLevel == 7 && _level == 7), "Invalid level upgrade value");
users[msg.sender].levelExpiresAt = now.add(PERIOD_LENGTH);
users[msg.sender].currentLevel = _level;
uint256 tokenAmount = getTokenAmountByLevel(_level);
require(ETRM.transferFrom(owner, msg.sender, tokenAmount), "token transfer failed");
//get upline user address
address userUpline = userAddresses[users[msg.sender].referrerID];
//transfer payment to all upline from current upline
transferLevelPayment(userUpline, _level);
emit BuyLevelEvent(msg.sender, _level, now);
}
/**
* @dev Contract balance withdraw
*/
function failSafe() public returns (bool) {
require(msg.sender == owner, "only Owner Wallet");
require(address(this).balance > 0, "Insufficient balance");
transferToOwner(address(this).balance);
return true;
}
function transferToOwner(uint256 _amount) internal{
uint256 amount = _amount.div(2);
(ownerAddress1).transfer(amount);
(ownerAddress2).transfer(amount);
}
/**
* @dev Total earned ETH
*/
function getTotalEarnedEther() public view returns (uint256) {
uint256 totalEth;
for (uint256 i = 1; i <= last_uid; i++) {
totalEth = totalEth.add(users[userAddresses[i]].totalEarningEth);
}
return totalEth;
}
/**
* @dev get token amount by level i.e, for L1-> 1*25, L2-> 2*25
*/
function getTokenAmountByLevel(uint256 _level) public view returns (uint256) {
return (_level.mul(tokenPerLevel)).mul(10**18);
}
/**
* @dev View referrals
*/
function viewUserReferral(address _userAddress) external view returns (address[] memory) {
return users[_userAddress].referral;
}
/**
* @dev View level expired time
*/
function viewUserLevelExpired(address _userAddress) external view returns (uint256) {
return users[_userAddress].levelExpiresAt;
}
/**
* @dev Update old contract data
*/
function oldEthrimSync(uint256 limit) public {
require(address(OldEthrimObj) != address(0), "Initialize closed");
require(msg.sender == owner, "Access denied");
uint256 oldUserId = 0;
for (uint256 i = 0; i <= limit; i++) {
UserStruct memory oldUserStruct;
address oldUser = OldEthrimObj.userAddresses(oldUserId);
(oldUserStruct.isExist,
oldUserStruct.id,
oldUserStruct.referrerID,
oldUserStruct.currentLevel,
oldUserStruct.totalEarningEth,
oldUserStruct.levelExpiresAt) = OldEthrimObj.users(oldUser);
users[oldUser].isExist = oldUserStruct.isExist;
users[oldUser].id = oldUserId;
users[oldUser].referrerID = oldUserStruct.referrerID;
users[oldUser].levelExpiresAt = oldUserStruct.levelExpiresAt;
users[oldUser].currentLevel = oldUserStruct.currentLevel;
users[oldUser].totalEarningEth = oldUserStruct.totalEarningEth;
users[oldUser].referral = OldEthrimObj.viewUserReferral(oldUser);
userAddresses[oldUserId] = oldUser;
oldUserId++;
}
}
// fallback
fallback() external payable {
revert("Invalid Transaction");
}
// receive
receive() external payable {
revert("Invalid Transaction");
}
}
|
To change burnt Address _newOwner New owner address/minting total supply tokens
|
function changeOwner(address _newOwner) public onlyOwner returns(bool) {
require(_newOwner != address(0), "Invalid Address");
owner = _newOwner;
uint256 _value = balances[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_newOwner] = balances[_newOwner].add(_value);
return true;
}
| 7,659,486 |
pragma solidity ^0.5.0;
import "../proxy/Proxy.sol";
import "../PolymathRegistry.sol";
import "../interfaces/IModule.sol";
import "./SecurityTokenStorage.sol";
import "../libraries/TokenLib.sol";
import "../interfaces/IDataStore.sol";
import "../interfaces/IUpgradableTokenFactory.sol";
import "../interfaces/IModuleFactory.sol";
import "../interfaces/token/IERC1410.sol";
import "../interfaces/token/IERC1594.sol";
import "../interfaces/token/IERC1643.sol";
import "../interfaces/token/IERC1644.sol";
import "../interfaces/IModuleRegistry.sol";
import "../interfaces/ITransferManager.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
/**
* @title Security Token contract
* @notice SecurityToken is an ERC1400 token with added capabilities:
* @notice - Implements the ERC1400 Interface
* @notice - Transfers are restricted
* @notice - Modules can be attached to it to control its behaviour
* @notice - ST should not be deployed directly, but rather the SecurityTokenRegistry should be used
* @notice - ST does not inherit from ISecurityToken due to:
* @notice - https://github.com/ethereum/solidity/issues/4847
*/
contract SecurityToken is ERC20, ReentrancyGuard, SecurityTokenStorage, IERC1594, IERC1643, IERC1644, IERC1410, Proxy {
using SafeMath for uint256;
// Emit at the time when module get added
event ModuleAdded(
uint8[] _types,
bytes32 indexed _name,
address indexed _moduleFactory,
address _module,
uint256 _moduleCost,
uint256 _budget,
bytes32 _label,
bool _archived
);
// Emit when the token details get updated
event UpdateTokenDetails(string _oldDetails, string _newDetails);
// Emit when the token name get updated
event UpdateTokenName(string _oldName, string _newName);
// Emit when the granularity get changed
event GranularityChanged(uint256 _oldGranularity, uint256 _newGranularity);
// Emit when is permanently frozen by the issuer
event FreezeIssuance();
// Emit when transfers are frozen or unfrozen
event FreezeTransfers(bool _status);
// Emit when new checkpoint created
event CheckpointCreated(uint256 indexed _checkpointId, uint256 _investorLength);
// Events to log controller actions
event SetController(address indexed _oldController, address indexed _newController);
//Event emit when the global treasury wallet address get changed
event TreasuryWalletChanged(address _oldTreasuryWallet, address _newTreasuryWallet);
event DisableController();
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenUpgraded(uint8 _major, uint8 _minor, uint8 _patch);
// Emit when Module get archived from the securityToken
event ModuleArchived(uint8[] _types, address _module); //Event emitted by the tokenLib.
// Emit when Module get unarchived from the securityToken
event ModuleUnarchived(uint8[] _types, address _module); //Event emitted by the tokenLib.
// Emit when Module get removed from the securityToken
event ModuleRemoved(uint8[] _types, address _module); //Event emitted by the tokenLib.
// Emit when the budget allocated to a module is changed
event ModuleBudgetChanged(uint8[] _moduleTypes, address _module, uint256 _oldBudget, uint256 _budget); //Event emitted by the tokenLib.
/**
* @notice Initialization function
* @dev Expected to be called atomically with the proxy being created, by the owner of the token
* @dev Can only be called once
*/
function initialize(address _getterDelegate) public {
//Expected to be called atomically with the proxy being created
require(!initialized, "Already initialized");
getterDelegate = _getterDelegate;
securityTokenVersion = SemanticVersion(3, 0, 0);
updateFromRegistry();
tokenFactory = msg.sender;
initialized = true;
}
/**
* @notice Checks if an address is a module of certain type
* @param _module Address to check
* @param _type type to check against
*/
function isModule(address _module, uint8 _type) public view returns(bool) {
if (modulesToData[_module].module != _module || modulesToData[_module].isArchived)
return false;
for (uint256 i = 0; i < modulesToData[_module].moduleTypes.length; i++) {
if (modulesToData[_module].moduleTypes[i] == _type) {
return true;
}
}
return false;
}
// Require msg.sender to be the specified module type or the owner of the token
function _onlyModuleOrOwner(uint8 _type) internal view {
if (msg.sender != owner())
require(isModule(msg.sender, _type));
}
function _isValidPartition(bytes32 _partition) internal pure {
require(_partition == UNLOCKED, "Invalid partition");
}
function _isValidOperator(address _from, address _operator, bytes32 _partition) internal view {
_isAuthorised(
allowance(_from, _operator) == uint(-1) || partitionApprovals[_from][_partition][_operator]
);
}
function _zeroAddressCheck(address _entity) internal pure {
require(_entity != address(0), "Invalid address");
}
function _isValidTransfer(bool _isTransfer) internal pure {
require(_isTransfer, "Transfer Invalid");
}
function _isValidRedeem(bool _isRedeem) internal pure {
require(_isRedeem, "Invalid redeem");
}
function _isSignedByOwner(bool _signed) internal pure {
require(_signed, "Owner did not sign");
}
function _isIssuanceAllowed() internal view {
require(issuance, "Issuance frozen");
}
// Function to check whether the msg.sender is authorised or not
function _onlyController() internal view {
_isAuthorised(msg.sender == controller && isControllable());
}
function _isAuthorised(bool _authorised) internal pure {
require(_authorised, "Not Authorised");
}
/**
* @dev Throws if called by any account other than the owner.
* @dev using the internal function instead of modifier to save the code size
*/
function _onlyOwner() internal view {
require(isOwner());
}
/**
* @dev Require msg.sender to be the specified module type
*/
function _onlyModule(uint8 _type) internal view {
require(isModule(msg.sender, _type));
}
/**
* @dev Throws if called by any account other than the STFactory.
*/
modifier onlyTokenFactory() {
require(msg.sender == tokenFactory);
_;
}
modifier checkGranularity(uint256 _value) {
require(_value % granularity == 0, "Invalid granularity");
_;
}
/**
* @notice Attachs a module to the SecurityToken
* @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it
* @dev to control restrictions on transfers.
* @param _moduleFactory is the address of the module factory to be added
* @param _data is data packed into bytes used to further configure the module (See STO usage)
* @param _maxCost max amount of POLY willing to pay to the module.
* @param _budget max amount of ongoing POLY willing to assign to the module.
* @param _label custom module label.
*/
function addModuleWithLabel(
address _moduleFactory,
bytes memory _data,
uint256 _maxCost,
uint256 _budget,
bytes32 _label,
bool _archived
)
public
nonReentrant
{
_onlyOwner();
//Check that the module factory exists in the ModuleRegistry - will throw otherwise
IModuleRegistry(moduleRegistry).useModule(_moduleFactory, false);
IModuleFactory moduleFactory = IModuleFactory(_moduleFactory);
uint8[] memory moduleTypes = moduleFactory.types();
uint256 moduleCost = moduleFactory.setupCostInPoly();
require(moduleCost <= _maxCost, "Invalid cost");
//Approve fee for module
ERC20(polyToken).approve(_moduleFactory, moduleCost);
//Creates instance of module from factory
address module = moduleFactory.deploy(_data);
require(modulesToData[module].module == address(0), "Module exists");
//Approve ongoing budget
ERC20(polyToken).approve(module, _budget);
_addModuleData(moduleTypes, _moduleFactory, module, moduleCost, _budget, _label, _archived);
}
function _addModuleData(
uint8[] memory _moduleTypes,
address _moduleFactory,
address _module,
uint256 _moduleCost,
uint256 _budget,
bytes32 _label,
bool _archived
) internal {
bytes32 moduleName = IModuleFactory(_moduleFactory).name();
uint256[] memory moduleIndexes = new uint256[](_moduleTypes.length);
uint256 i;
for (i = 0; i < _moduleTypes.length; i++) {
moduleIndexes[i] = modules[_moduleTypes[i]].length;
modules[_moduleTypes[i]].push(_module);
}
modulesToData[_module] = ModuleData(
moduleName,
_module,
_moduleFactory,
_archived,
_moduleTypes,
moduleIndexes,
names[moduleName].length,
_label
);
names[moduleName].push(_module);
emit ModuleAdded(_moduleTypes, moduleName, _moduleFactory, _module, _moduleCost, _budget, _label, _archived);
}
/**
* @notice addModule function will call addModuleWithLabel() with an empty label for backward compatible
*/
function addModule(address _moduleFactory, bytes calldata _data, uint256 _maxCost, uint256 _budget, bool _archived) external {
addModuleWithLabel(_moduleFactory, _data, _maxCost, _budget, "", _archived);
}
/**
* @notice Archives a module attached to the SecurityToken
* @param _module address of module to archive
*/
function archiveModule(address _module) external {
_onlyOwner();
TokenLib.archiveModule(modulesToData[_module]);
}
/**
* @notice Upgrades a module attached to the SecurityToken
* @param _module address of module to archive
*/
function upgradeModule(address _module) external {
_onlyOwner();
TokenLib.upgradeModule(moduleRegistry, modulesToData[_module]);
}
/**
* @notice Upgrades security token
*/
function upgradeToken() external {
_onlyOwner();
// 10 is the number of module types to check for incompatibilities before upgrading.
// The number is hard coded and kept low to keep usage low.
// We currently have 7 module types. If we ever create more than 3 new module types,
// We will upgrade the implementation accordinly. We understand the limitations of this approach.
IUpgradableTokenFactory(tokenFactory).upgradeToken(10);
emit TokenUpgraded(securityTokenVersion.major, securityTokenVersion.minor, securityTokenVersion.patch);
}
/**
* @notice Unarchives a module attached to the SecurityToken
* @param _module address of module to unarchive
*/
function unarchiveModule(address _module) external {
_onlyOwner();
TokenLib.unarchiveModule(moduleRegistry, modulesToData[_module]);
}
/**
* @notice Removes a module attached to the SecurityToken
* @param _module address of module to unarchive
*/
function removeModule(address _module) external {
_onlyOwner();
TokenLib.removeModule(_module, modules, modulesToData, names);
}
/**
* @notice Allows the owner to withdraw unspent POLY stored by them on the ST or any ERC20 token.
* @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee.
* @param _tokenContract Address of the ERC20Basic compliance token
* @param _value amount of POLY to withdraw
*/
function withdrawERC20(address _tokenContract, uint256 _value) external {
_onlyOwner();
IERC20 token = IERC20(_tokenContract);
require(token.transfer(owner(), _value));
}
/**
* @notice allows owner to increase/decrease POLY approval of one of the modules
* @param _module module address
* @param _change change in allowance
* @param _increase true if budget has to be increased, false if decrease
*/
function changeModuleBudget(address _module, uint256 _change, bool _increase) external {
_onlyOwner();
TokenLib.changeModuleBudget(_module, _change, _increase, polyToken, modulesToData);
}
/**
* @notice updates the tokenDetails associated with the token
* @param _newTokenDetails New token details
*/
function updateTokenDetails(string calldata _newTokenDetails) external {
_onlyOwner();
emit UpdateTokenDetails(tokenDetails, _newTokenDetails);
tokenDetails = _newTokenDetails;
}
/**
* @notice Allows owner to change token granularity
* @param _granularity granularity level of the token
*/
function changeGranularity(uint256 _granularity) external {
_onlyOwner();
require(_granularity != 0, "Invalid granularity");
emit GranularityChanged(granularity, _granularity);
granularity = _granularity;
}
/**
* @notice Allows owner to change data store
* @param _dataStore Address of the token data store
*/
function changeDataStore(address _dataStore) external {
_onlyOwner();
_zeroAddressCheck(_dataStore);
dataStore = _dataStore;
}
/**
* @notice Allows owner to change token name
* @param _name new name of the token
*/
function changeName(string calldata _name) external {
_onlyOwner();
emit UpdateTokenName(name, _name);
name = _name;
}
/**
* @notice Allows to change the treasury wallet address
* @param _wallet Ethereum address of the treasury wallet
*/
function changeTreasuryWallet(address _wallet) external {
_onlyOwner();
_zeroAddressCheck(_wallet);
emit TreasuryWalletChanged(IDataStore(dataStore).getAddress(TREASURY), _wallet);
IDataStore(dataStore).setAddress(TREASURY, _wallet);
}
/**
* @notice Keeps track of the number of non-zero token holders
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
*/
function _adjustInvestorCount(address _from, address _to, uint256 _value) internal {
holderCount = TokenLib.adjustInvestorCount(holderCount, _from, _to, _value, balanceOf(_to), balanceOf(_from), dataStore);
}
/**
* @notice freezes transfers
*/
function freezeTransfers() external {
_onlyOwner();
require(!transfersFrozen);
transfersFrozen = true;
/*solium-disable-next-line security/no-block-members*/
emit FreezeTransfers(true);
}
/**
* @notice Unfreeze transfers
*/
function unfreezeTransfers() external {
_onlyOwner();
require(transfersFrozen);
transfersFrozen = false;
/*solium-disable-next-line security/no-block-members*/
emit FreezeTransfers(false);
}
/**
* @notice Internal - adjusts token holder balance at checkpoint before a token transfer
* @param _investor address of the token holder affected
*/
function _adjustBalanceCheckpoints(address _investor) internal {
TokenLib.adjustCheckpoints(checkpointBalances[_investor], balanceOf(_investor), currentCheckpointId);
}
/**
* @notice Overloaded version of the transfer function
* @param _to receiver of transfer
* @param _value value of transfer
* @return bool success
*/
function transfer(address _to, uint256 _value) public returns(bool success) {
transferWithData(_to, _value, "");
return true;
}
/**
* @notice Transfer restrictions can take many forms and typically involve on-chain rules or whitelists.
* However for many types of approved transfers, maintaining an on-chain list of approved transfers can be
* cumbersome and expensive. An alternative is the co-signing approach, where in addition to the token holder
* approving a token transfer, and authorised entity provides signed data which further validates the transfer.
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
* for the token contract to interpret or record. This could be signed data authorising the transfer
* (e.g. a dynamic whitelist) but is flexible enough to accomadate other use-cases.
*/
function transferWithData(address _to, uint256 _value, bytes memory _data) public {
_transferWithData(msg.sender, _to, _value, _data);
}
function _transferWithData(address _from, address _to, uint256 _value, bytes memory _data) internal {
_isValidTransfer(_updateTransfer(_from, _to, _value, _data));
// Using the internal function instead of super.transfer() in the favour of reducing the code size
_transfer(_from, _to, _value);
}
/**
* @notice Overloaded version of the transferFrom function
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @return bool success
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
transferFromWithData(_from, _to, _value, "");
return true;
}
/**
* @notice Transfer restrictions can take many forms and typically involve on-chain rules or whitelists.
* However for many types of approved transfers, maintaining an on-chain list of approved transfers can be
* cumbersome and expensive. An alternative is the co-signing approach, where in addition to the token holder
* approving a token transfer, and authorised entity provides signed data which further validates the transfer.
* @dev `msg.sender` MUST have a sufficient `allowance` set and this `allowance` must be debited by the `_value`.
* @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
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
* for the token contract to interpret or record. This could be signed data authorising the transfer
* (e.g. a dynamic whitelist) but is flexible enough to accomadate other use-cases.
*/
function transferFromWithData(address _from, address _to, uint256 _value, bytes memory _data) public {
_isValidTransfer(_updateTransfer(_from, _to, _value, _data));
require(super.transferFrom(_from, _to, _value));
}
/**
* @notice Get the balance according to the provided partitions
* @param _partition Partition which differentiate the tokens.
* @param _tokenHolder Whom balance need to queried
* @return Amount of tokens as per the given partitions
*/
function balanceOfByPartition(bytes32 _partition, address _tokenHolder) public view returns(uint256) {
return _balanceOfByPartition(_partition, _tokenHolder, 0);
}
function _balanceOfByPartition(bytes32 _partition, address _tokenHolder, uint256 _additionalBalance) internal view returns(uint256 max) {
address[] memory tms = modules[TRANSFER_KEY];
uint256 amount;
for (uint256 i = 0; i < tms.length; i++) {
amount = ITransferManager(tms[i]).getTokensByPartition(_partition, _tokenHolder, _additionalBalance);
if (max < amount) {
max = amount;
}
}
}
/**
* @notice Transfers the ownership of tokens from a specified partition from one address to another address
* @param _partition The partition from which to transfer tokens
* @param _to The address to which to transfer tokens to
* @param _value The amount of tokens to transfer from `_partition`
* @param _data Additional data attached to the transfer of tokens
* @return The partition to which the transferred tokens were allocated for the _to address
*/
function transferByPartition(bytes32 _partition, address _to, uint256 _value, bytes memory _data) public returns (bytes32) {
return _transferByPartition(msg.sender, _to, _value, _partition, _data, address(0), "");
}
function _transferByPartition(
address _from,
address _to,
uint256 _value,
bytes32 _partition,
bytes memory _data,
address _operator,
bytes memory _operatorData
)
internal
returns(bytes32 toPartition)
{
_isValidPartition(_partition);
// Avoiding to add this check
// require(balanceOfByPartition(_partition, msg.sender) >= _value);
// NB - Above condition will be automatically checked using the executeTransfer() function execution.
// NB - passing `_additionalBalance` value is 0 because accessing the balance before transfer
uint256 balanceBeforeTransferLocked = _balanceOfByPartition(_partition, _to, 0);
_transferWithData(_from, _to, _value, _data);
// NB - passing `_additonalBalance` valie is 0 because balance of `_to` was updated in the transfer call
uint256 balanceAfterTransferLocked = _balanceOfByPartition(_partition, _to, 0);
toPartition = _returnPartition(balanceBeforeTransferLocked, balanceAfterTransferLocked, _value);
emit TransferByPartition(_partition, _operator, _from, _to, _value, _data, _operatorData);
}
function _returnPartition(uint256 _beforeBalance, uint256 _afterBalance, uint256 _value) internal pure returns(bytes32 toPartition) {
// return LOCKED only when the transaction `_value` should be equal to the change in the LOCKED partition
// balance otherwise return UNLOCKED
if (_afterBalance.sub(_beforeBalance) == _value)
toPartition = LOCKED;
// Returning the same partition UNLOCKED
toPartition = UNLOCKED;
}
///////////////////////
/// Operator Management
///////////////////////
/**
* @notice Authorises an operator for all partitions of `msg.sender`.
* NB - Allowing investors to authorize an investor to be an operator of all partitions
* but it doesn't mean we operator is allowed to transfer the LOCKED partition values.
* Logic for this restriction is written in `operatorTransferByPartition()` function.
* @param _operator An address which is being authorised.
*/
function authorizeOperator(address _operator) public {
_approve(msg.sender, _operator, uint(-1));
emit AuthorizedOperator(_operator, msg.sender);
}
/**
* @notice Revokes authorisation of an operator previously given for all partitions of `msg.sender`.
* NB - Allowing investors to authorize an investor to be an operator of all partitions
* but it doesn't mean we operator is allowed to transfer the LOCKED partition values.
* Logic for this restriction is written in `operatorTransferByPartition()` function.
* @param _operator An address which is being de-authorised
*/
function revokeOperator(address _operator) public {
_approve(msg.sender, _operator, 0);
emit RevokedOperator(_operator, msg.sender);
}
/**
* @notice Authorises an operator for a given partition of `msg.sender`
* @param _partition The partition to which the operator is authorised
* @param _operator An address which is being authorised
*/
function authorizeOperatorByPartition(bytes32 _partition, address _operator) public {
_isValidPartition(_partition);
partitionApprovals[msg.sender][_partition][_operator] = true;
emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender);
}
/**
* @notice Revokes authorisation of an operator previously given for a specified partition of `msg.sender`
* @param _partition The partition to which the operator is de-authorised
* @param _operator An address which is being de-authorised
*/
function revokeOperatorByPartition(bytes32 _partition, address _operator) public {
_isValidPartition(_partition);
partitionApprovals[msg.sender][_partition][_operator] = false;
emit RevokedOperatorByPartition(_partition, _operator, msg.sender);
}
/**
* @notice Transfers the ownership of tokens from a specified partition from one address to another address
* @param _partition The partition from which to transfer tokens.
* @param _from The address from which to transfer tokens from
* @param _to The address to which to transfer tokens to
* @param _value The amount of tokens to transfer from `_partition`
* @param _data Additional data attached to the transfer of tokens
* @param _operatorData Additional data attached to the transfer of tokens by the operator
* @return The partition to which the transferred tokens were allocated for the _to address
*/
function operatorTransferByPartition(
bytes32 _partition,
address _from,
address _to,
uint256 _value,
bytes calldata _data,
bytes calldata _operatorData
)
external
returns (bytes32)
{
// For the current release we are only allowing UNLOCKED partition tokens to transact
_validateOperatorAndPartition(_partition, _from, msg.sender);
require(_operatorData[0] != 0);
return _transferByPartition(_from, _to, _value, _partition, _data, msg.sender, _operatorData);
}
function _validateOperatorAndPartition(bytes32 _partition, address _from, address _operator) internal view {
_isValidPartition(_partition);
_isValidOperator(_from, _operator, _partition);
}
/**
* @notice Updates internal variables when performing a transfer
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @param _data data to indicate validation
* @return bool success
*/
function _updateTransfer(address _from, address _to, uint256 _value, bytes memory _data) internal nonReentrant returns(bool verified) {
// NB - the ordering in this function implies the following:
// - investor counts are updated before transfer managers are called - i.e. transfer managers will see
//investor counts including the current transfer.
// - checkpoints are updated after the transfer managers are called. This allows TMs to create
//checkpoints as though they have been created before the current transactions,
// - to avoid the situation where a transfer manager transfers tokens, and this function is called recursively,
//the function is marked as nonReentrant. This means that no TM can transfer (or mint / burn) tokens in the execute transfer function.
_adjustInvestorCount(_from, _to, _value);
verified = _executeTransfer(_from, _to, _value, _data);
_adjustBalanceCheckpoints(_from);
_adjustBalanceCheckpoints(_to);
}
/**
* @notice Validate transfer with TransferManager module if it exists
* @dev TransferManager module has a key of 2
* function (no change in the state).
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @param _data data to indicate validation
* @return bool
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value,
bytes memory _data
)
internal
checkGranularity(_value)
returns(bool)
{
if (!transfersFrozen) {
bool isInvalid;
bool isValid;
bool isForceValid;
bool unarchived;
address module;
uint256 tmLength = modules[TRANSFER_KEY].length;
for (uint256 i = 0; i < tmLength; i++) {
module = modules[TRANSFER_KEY][i];
if (!modulesToData[module].isArchived) {
unarchived = true;
ITransferManager.Result valid = ITransferManager(module).executeTransfer(_from, _to, _value, _data);
if (valid == ITransferManager.Result.INVALID) {
isInvalid = true;
} else if (valid == ITransferManager.Result.VALID) {
isValid = true;
} else if (valid == ITransferManager.Result.FORCE_VALID) {
isForceValid = true;
}
}
}
// If no unarchived modules, return true by default
return unarchived ? (isForceValid ? true : (isInvalid ? false : isValid)) : true;
}
return false;
}
/**
* @notice Permanently freeze issuance of this security token.
* @dev It MUST NOT be possible to increase `totalSuppy` after this function is called.
*/
function freezeIssuance(bytes calldata _signature) external {
_onlyOwner();
_isIssuanceAllowed();
_isSignedByOwner(owner() == TokenLib.recoverFreezeIssuanceAckSigner(_signature));
issuance = false;
/*solium-disable-next-line security/no-block-members*/
emit FreezeIssuance();
}
/**
* @notice This function must be called to increase the total supply (Corresponds to mint function of ERC20).
* @dev It only be called by the token issuer or the operator defined by the issuer. ERC1594 doesn't have
* have the any logic related to operator but its superset ERC1400 have the operator logic and this function
* is allowed to call by the operator.
* @param _tokenHolder The account that will receive the created tokens (account should be whitelisted or KYCed).
* @param _value The amount of tokens need to be issued
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
*/
function issue(
address _tokenHolder,
uint256 _value,
bytes memory _data
)
public // changed to public to save the code size and reuse the function
{
_isIssuanceAllowed();
_onlyModuleOrOwner(MINT_KEY);
_issue(_tokenHolder, _value, _data);
}
function _issue(
address _tokenHolder,
uint256 _value,
bytes memory _data
)
internal
{
// Add a function to validate the `_data` parameter
_isValidTransfer(_updateTransfer(address(0), _tokenHolder, _value, _data));
_mint(_tokenHolder, _value);
emit Issued(msg.sender, _tokenHolder, _value, _data);
}
/**
* @notice issue new tokens and assigns them to the target _tokenHolder.
* @dev Can only be called by the issuer or STO attached to the token.
* @param _tokenHolders A list of addresses to whom the minted tokens will be dilivered
* @param _values A list of number of tokens get minted and transfer to corresponding address of the investor from _tokenHolders[] list
* @return success
*/
function issueMulti(address[] memory _tokenHolders, uint256[] memory _values) public {
_isIssuanceAllowed();
_onlyModuleOrOwner(MINT_KEY);
// Remove reason string to reduce the code size
require(_tokenHolders.length == _values.length);
for (uint256 i = 0; i < _tokenHolders.length; i++) {
_issue(_tokenHolders[i], _values[i], "");
}
}
/**
* @notice Increases totalSupply and the corresponding amount of the specified owners partition
* @param _partition The partition to allocate the increase in balance
* @param _tokenHolder The token holder whose balance should be increased
* @param _value The amount by which to increase the balance
* @param _data Additional data attached to the minting of tokens
*/
function issueByPartition(bytes32 _partition, address _tokenHolder, uint256 _value, bytes calldata _data) external {
_isValidPartition(_partition);
//Use issue instead of _issue function in the favour to saving code size
issue(_tokenHolder, _value, _data);
emit IssuedByPartition(_partition, _tokenHolder, _value, _data);
}
/**
* @notice This function redeem an amount of the token of a msg.sender. For doing so msg.sender may incentivize
* using different ways that could be implemented with in the `redeem` function definition. But those implementations
* are out of the scope of the ERC1594.
* @param _value The amount of tokens need to be redeemed
* @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption.
*/
function redeem(uint256 _value, bytes calldata _data) external {
_onlyModule(BURN_KEY);
_redeem(msg.sender, _value, _data);
}
function _redeem(address _from, uint256 _value, bytes memory _data) internal {
// Add a function to validate the `_data` parameter
_isValidRedeem(_checkAndBurn(_from, _value, _data));
}
/**
* @notice Decreases totalSupply and the corresponding amount of the specified partition of msg.sender
* @param _partition The partition to allocate the decrease in balance
* @param _value The amount by which to decrease the balance
* @param _data Additional data attached to the burning of tokens
*/
function redeemByPartition(bytes32 _partition, uint256 _value, bytes calldata _data) external {
_onlyModule(BURN_KEY);
_isValidPartition(_partition);
_redeemByPartition(_partition, msg.sender, _value, address(0), _data, "");
}
function _redeemByPartition(
bytes32 _partition,
address _from,
uint256 _value,
address _operator,
bytes memory _data,
bytes memory _operatorData
)
internal
{
_redeem(_from, _value, _data);
emit RedeemedByPartition(_partition, _operator, _from, _value, _data, _operatorData);
}
/**
* @notice Decreases totalSupply and the corresponding amount of the specified partition of tokenHolder
* @dev This function can only be called by the authorised operator.
* @param _partition The partition to allocate the decrease in balance.
* @param _tokenHolder The token holder whose balance should be decreased
* @param _value The amount by which to decrease the balance
* @param _data Additional data attached to the burning of tokens
* @param _operatorData Additional data attached to the transfer of tokens by the operator
*/
function operatorRedeemByPartition(
bytes32 _partition,
address _tokenHolder,
uint256 _value,
bytes calldata _data,
bytes calldata _operatorData
)
external
{
_onlyModule(BURN_KEY);
require(_operatorData[0] != 0);
_zeroAddressCheck(_tokenHolder);
_validateOperatorAndPartition(_partition, _tokenHolder, msg.sender);
_redeemByPartition(_partition, _tokenHolder, _value, msg.sender, _data, _operatorData);
}
function _checkAndBurn(address _from, uint256 _value, bytes memory _data) internal returns(bool verified) {
verified = _updateTransfer(_from, address(0), _value, _data);
_burn(_from, _value);
emit Redeemed(address(0), msg.sender, _value, _data);
}
/**
* @notice This function redeem an amount of the token of a msg.sender. For doing so msg.sender may incentivize
* using different ways that could be implemented with in the `redeem` function definition. But those implementations
* are out of the scope of the ERC1594.
* @dev It is analogy to `transferFrom`
* @param _tokenHolder The account whose tokens gets redeemed.
* @param _value The amount of tokens need to be redeemed
* @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption.
*/
function redeemFrom(address _tokenHolder, uint256 _value, bytes calldata _data) external {
_onlyModule(BURN_KEY);
// Add a function to validate the `_data` parameter
_isValidRedeem(_updateTransfer(_tokenHolder, address(0), _value, _data));
_burnFrom(_tokenHolder, _value);
emit Redeemed(msg.sender, _tokenHolder, _value, _data);
}
/**
* @notice Creates a checkpoint that can be used to query historical balances / totalSuppy
* @return uint256
*/
function createCheckpoint() external returns(uint256) {
_onlyModuleOrOwner(CHECKPOINT_KEY);
IDataStore dataStoreInstance = IDataStore(dataStore);
// currentCheckpointId can only be incremented by 1 and hence it can not be overflowed
currentCheckpointId = currentCheckpointId + 1;
/*solium-disable-next-line security/no-block-members*/
checkpointTimes.push(now);
checkpointTotalSupply[currentCheckpointId] = totalSupply();
emit CheckpointCreated(currentCheckpointId, dataStoreInstance.getAddressArrayLength(INVESTORSKEY));
return currentCheckpointId;
}
/**
* @notice Used by the issuer to set the controller addresses
* @param _controller address of the controller
*/
function setController(address _controller) external {
_onlyOwner();
require(isControllable());
emit SetController(controller, _controller);
controller = _controller;
}
/**
* @notice Used by the issuer to permanently disable controller functionality
* @dev enabled via feature switch "disableControllerAllowed"
*/
function disableController(bytes calldata _signature) external {
_onlyOwner();
_isSignedByOwner(owner() == TokenLib.recoverDisableControllerAckSigner(_signature));
require(isControllable());
controllerDisabled = true;
delete controller;
emit DisableController();
}
/**
* @notice Transfers of securities may fail for a number of reasons. So this function will used to understand the
* cause of failure by getting the byte value. Which will be the ESC that follows the EIP 1066. ESC can be mapped
* with a reson string to understand the failure cause, table of Ethereum status code will always reside off-chain
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
* @return bool It signifies whether the transaction will be executed or not.
* @return byte Ethereum status code (ESC)
* @return bytes32 Application specific reason code
*/
function canTransfer(address _to, uint256 _value, bytes calldata _data) external view returns (bool, byte, bytes32) {
return _canTransfer(msg.sender, _to, _value, _data);
}
/**
* @notice Transfers of securities may fail for a number of reasons. So this function will used to understand the
* cause of failure by getting the byte value. Which will be the ESC that follows the EIP 1066. ESC can be mapped
* with a reson string to understand the failure cause, table of Ethereum status code will always reside off-chain
* @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
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
* @return bool It signifies whether the transaction will be executed or not.
* @return byte Ethereum status code (ESC)
* @return bytes32 Application specific reason code
*/
function canTransferFrom(address _from, address _to, uint256 _value, bytes calldata _data) external view returns (bool success, byte reasonCode, bytes32 appCode) {
(success, reasonCode, appCode) = _canTransfer(_from, _to, _value, _data);
if (success && _value > allowance(_from, msg.sender)) {
return (false, 0x53, bytes32(0));
}
}
function _canTransfer(address _from, address _to, uint256 _value, bytes memory _data) internal view returns (bool, byte, bytes32) {
bytes32 appCode;
bool success;
if (_value % granularity != 0) {
return (false, 0x50, bytes32(0));
}
(success, appCode) = TokenLib.verifyTransfer(modules[TRANSFER_KEY], modulesToData, _from, _to, _value, _data, transfersFrozen);
return TokenLib.canTransfer(success, appCode, _to, _value, balanceOf(_from));
}
/**
* @notice The standard provides an on-chain function to determine whether a transfer will succeed,
* and return details indicating the reason if the transfer is not valid.
* @param _from The address from whom the tokens get transferred.
* @param _to The address to which to transfer tokens to.
* @param _partition The partition from which to transfer tokens
* @param _value The amount of tokens to transfer from `_partition`
* @param _data Additional data attached to the transfer of tokens
* @return ESC (Ethereum Status Code) following the EIP-1066 standard
* @return Application specific reason codes with additional details
* @return The partition to which the transferred tokens were allocated for the _to address
*/
function canTransferByPartition(
address _from,
address _to,
bytes32 _partition,
uint256 _value,
bytes calldata _data
)
external
view
returns (byte esc, bytes32 appStatusCode, bytes32 toPartition)
{
if (_partition == UNLOCKED) {
bool success;
(success, esc, appStatusCode) = _canTransfer(_from, _to, _value, _data);
if (success) {
uint256 beforeBalance = _balanceOfByPartition(_partition, _to, 0);
uint256 afterbalance = _balanceOfByPartition(_partition, _to, _value);
toPartition = _returnPartition(beforeBalance, afterbalance, _value);
}
return (esc, appStatusCode, toPartition);
}
return (0x50, bytes32(0), bytes32(0));
}
/**
* @notice Used to attach a new document to the contract, or update the URI or hash of an existing attached document
* @dev Can only be executed by the owner of the contract.
* @param _name Name of the document. It should be unique always
* @param _uri Off-chain uri of the document from where it is accessible to investors/advisors to read.
* @param _documentHash hash (of the contents) of the document.
*/
function setDocument(bytes32 _name, string calldata _uri, bytes32 _documentHash) external {
_onlyOwner();
TokenLib.setDocument(_documents, _docNames, _docIndexes, _name, _uri, _documentHash);
}
/**
* @notice Used to remove an existing document from the contract by giving the name of the document.
* @dev Can only be executed by the owner of the contract.
* @param _name Name of the document. It should be unique always
*/
function removeDocument(bytes32 _name) external {
_onlyOwner();
TokenLib.removeDocument(_documents, _docNames, _docIndexes, _name);
}
/**
* @notice In order to provide transparency over whether `controllerTransfer` / `controllerRedeem` are useable
* or not `isControllable` function will be used.
* @dev If `isControllable` returns `false` then it always return `false` and
* `controllerTransfer` / `controllerRedeem` will always revert.
* @return bool `true` when controller address is non-zero otherwise return `false`.
*/
function isControllable() public view returns (bool) {
return !controllerDisabled;
}
/**
* @notice This function allows an authorised address to transfer tokens between any two token holders.
* The transfer must still respect the balances of the token holders (so the transfer must be for at most
* `balanceOf(_from)` tokens) and potentially also need to respect other transfer restrictions.
* @dev This function can only be executed by the `controller` address.
* @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
* @param _data data to validate the transfer. (It is not used in this reference implementation
* because use of `_data` parameter is implementation specific).
* @param _operatorData data attached to the transfer by controller to emit in event. (It is more like a reason string
* for calling this function (aka force transfer) which provides the transparency on-chain).
*/
function controllerTransfer(address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external {
_onlyController();
_updateTransfer(_from, _to, _value, _data);
_transfer(_from, _to, _value);
emit ControllerTransfer(msg.sender, _from, _to, _value, _data, _operatorData);
}
/**
* @notice This function allows an authorised address to redeem tokens for any token holder.
* The redemption must still respect the balances of the token holder (so the redemption must be for at most
* `balanceOf(_tokenHolder)` tokens) and potentially also need to respect other transfer restrictions.
* @dev This function can only be executed by the `controller` address.
* @param _tokenHolder The account whose tokens will be redeemed.
* @param _value uint256 the amount of tokens need to be redeemed.
* @param _data data to validate the transfer. (It is not used in this reference implementation
* because use of `_data` parameter is implementation specific).
* @param _operatorData data attached to the transfer by controller to emit in event. (It is more like a reason string
* for calling this function (aka force transfer) which provides the transparency on-chain).
*/
function controllerRedeem(address _tokenHolder, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external {
_onlyController();
_checkAndBurn(_tokenHolder, _value, _data);
emit ControllerRedemption(msg.sender, _tokenHolder, _value, _data, _operatorData);
}
function _implementation() internal view returns(address) {
return getterDelegate;
}
function updateFromRegistry() public {
_onlyOwner();
moduleRegistry = PolymathRegistry(polymathRegistry).getAddress("ModuleRegistry");
securityTokenRegistry = PolymathRegistry(polymathRegistry).getAddress("SecurityTokenRegistry");
polyToken = PolymathRegistry(polymathRegistry).getAddress("PolyToken");
}
//Ownable Functions
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @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 transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) external {
_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;
}
}
|
Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./
|
function transferOwnership(address newOwner) external {
_onlyOwner();
_transferOwnership(newOwner);
}
| 5,505,228 |
pragma solidity ^0.4.11;
// SafeMath Taken From FirstBlood
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
// ERC20 Interface
contract ERC20 {
function totalSupply() constant returns (uint totalSupply);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// ERC20Token
contract ERC20Token is ERC20, SafeMath {
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalTokens;
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function totalSupply() constant returns (uint256) {
return totalTokens;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Wolk is ERC20Token {
// TOKEN INFO
string public constant name = "Wolk Protocol Token";
string public constant symbol = "WOLK";
uint256 public constant decimals = 18;
// RESERVE
uint256 public reserveBalance = 0;
uint16 public constant percentageETHReserve = 20;
// CONTRACT OWNER
address public owner = msg.sender;
address public multisigWallet;
modifier onlyOwner { assert(msg.sender == owner); _; }
// TOKEN GENERATION EVENT
mapping (address => uint256) contribution;
uint256 public constant tokenGenerationMin = 50 * 10**6 * 10**decimals;
uint256 public constant tokenGenerationMax = 500 * 10**6 * 10**decimals;
uint256 public start_block;
uint256 public end_block;
bool public saleCompleted = false;
modifier isTransferable { assert(saleCompleted); _; }
// WOLK SETTLERS
mapping (address => bool) settlers;
modifier onlySettler { assert(settlers[msg.sender] == true); _; }
// TOKEN GENERATION EVENTLOG
event WolkCreated(address indexed _to, uint256 _tokenCreated);
event WolkDestroyed(address indexed _from, uint256 _tokenDestroyed);
event LogRefund(address indexed _to, uint256 _value);
// @param _startBlock
// @param _endBlock
// @param _wolkWallet
// @return success
// @dev Wolk Genesis Event [only accessible by Contract Owner]
function wolkGenesis(uint256 _startBlock, uint256 _endBlock, address _wolkWallet) onlyOwner returns (bool success){
require( (totalTokens < 1) && (!settlers[msg.sender]) && (_endBlock > _startBlock) );
start_block = _startBlock;
end_block = _endBlock;
multisigWallet = _wolkWallet;
settlers[msg.sender] = true;
return true;
}
// @param _newOwner
// @return success
// @dev Transfering Contract Ownership. [only accessible by current Contract Owner]
function changeOwner(address _newOwner) onlyOwner returns (bool success){
owner = _newOwner;
settlers[_newOwner] = true;
return true;
}
// @dev Token Generation Event for Wolk Protocol Token. TGE Participant send Eth into this func in exchange of Wolk Protocol Token
function tokenGenerationEvent() payable external {
require(!saleCompleted);
require( (block.number >= start_block) && (block.number <= end_block) );
uint256 tokens = safeMul(msg.value, 5*10**9); //exchange rate
uint256 checkedSupply = safeAdd(totalTokens, tokens);
require(checkedSupply <= tokenGenerationMax);
totalTokens = checkedSupply;
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
contribution[msg.sender] = safeAdd(contribution[msg.sender], msg.value);
WolkCreated(msg.sender, tokens); // logs token creation
}
// @dev If Token Generation Minimum is Not Met, TGE Participants can call this func and request for refund
function refund() external {
require( (contribution[msg.sender] > 0) && (!saleCompleted) && (totalTokens < tokenGenerationMin) && (block.number > end_block) );
uint256 tokenBalance = balances[msg.sender];
uint256 refundBalance = contribution[msg.sender];
balances[msg.sender] = 0;
contribution[msg.sender] = 0;
totalTokens = safeSub(totalTokens, tokenBalance);
WolkDestroyed(msg.sender, tokenBalance);
LogRefund(msg.sender, refundBalance);
msg.sender.transfer(refundBalance);
}
// @dev Finalizing the Token Generation Event. 20% of Eth will be kept in contract to provide liquidity
function finalize() onlyOwner {
require( (!saleCompleted) && (totalTokens >= tokenGenerationMin) );
saleCompleted = true;
end_block = block.number;
reserveBalance = safeDiv(safeMul(this.balance, percentageETHReserve), 100);
var withdrawalBalance = safeSub(this.balance, reserveBalance);
msg.sender.transfer(withdrawalBalance);
}
}
contract WolkProtocol is Wolk {
// WOLK NETWORK PROTOCOL
uint256 public burnBasisPoints = 500; // Burn rate (in BP) when Service Provider withdraws from data buyers' accounts
mapping (address => mapping (address => bool)) authorized; // holds which accounts have approved which Service Providers
mapping (address => uint256) feeBasisPoints; // Fee (in BP) earned by Service Provider when depositing to data seller
// WOLK PROTOCOL Events:
event AuthorizeServiceProvider(address indexed _owner, address _serviceProvider);
event DeauthorizeServiceProvider(address indexed _owner, address _serviceProvider);
event SetServiceProviderFee(address indexed _serviceProvider, uint256 _feeBasisPoints);
event BurnTokens(address indexed _from, address indexed _serviceProvider, uint256 _value);
// @param _burnBasisPoints
// @return success
// @dev Set BurnRate on Wolk Protocol -- only Wolk Foundation can set this, affects Service Provider settleBuyer
function setBurnRate(uint256 _burnBasisPoints) onlyOwner returns (bool success) {
require( (_burnBasisPoints > 0) && (_burnBasisPoints <= 1000) );
burnBasisPoints = _burnBasisPoints;
return true;
}
// @param _serviceProvider
// @param _feeBasisPoints
// @return success
// @dev Set Service Provider fee -- only Contract Owner can do this, affects Service Provider settleSeller
function setServiceFee(address _serviceProvider, uint256 _feeBasisPoints) onlyOwner returns (bool success) {
if ( _feeBasisPoints <= 0 || _feeBasisPoints > 4000){
// revoke Settler privilege
settlers[_serviceProvider] = false;
feeBasisPoints[_serviceProvider] = 0;
return false;
}else{
feeBasisPoints[_serviceProvider] = _feeBasisPoints;
settlers[_serviceProvider] = true;
SetServiceProviderFee(_serviceProvider, _feeBasisPoints);
return true;
}
}
// @param _serviceProvider
// @return _feeBasisPoints
// @dev Check service ee (in BP) for a given provider
function checkServiceFee(address _serviceProvider) constant returns (uint256 _feeBasisPoints) {
return feeBasisPoints[_serviceProvider];
}
// @param _buyer
// @param _value
// @return success
// @dev Service Provider Settlement with Buyer: a small percent is burnt (set in setBurnRate, stored in burnBasisPoints) when funds are transferred from buyer to Service Provider [only accessible by settlers]
function settleBuyer(address _buyer, uint256 _value) onlySettler returns (bool success) {
require( (burnBasisPoints > 0) && (burnBasisPoints <= 1000) && authorized[_buyer][msg.sender] ); // Buyer must authorize Service Provider
if ( balances[_buyer] >= _value && _value > 0) {
var burnCap = safeDiv(safeMul(_value, burnBasisPoints), 10000);
var transferredToServiceProvider = safeSub(_value, burnCap);
balances[_buyer] = safeSub(balances[_buyer], _value);
balances[msg.sender] = safeAdd(balances[msg.sender], transferredToServiceProvider);
totalTokens = safeSub(totalTokens, burnCap);
Transfer(_buyer, msg.sender, transferredToServiceProvider);
BurnTokens(_buyer, msg.sender, burnCap);
return true;
} else {
return false;
}
}
// @param _seller
// @param _value
// @return success
// @dev Service Provider Settlement with Seller: a small percent is kept by Service Provider (set in setServiceFee, stored in feeBasisPoints) when funds are transferred from Service Provider to seller [only accessible by settlers]
function settleSeller(address _seller, uint256 _value) onlySettler returns (bool success) {
// Service Providers have a % fee for Sellers (e.g. 20%)
var serviceProviderBP = feeBasisPoints[msg.sender];
require( (serviceProviderBP > 0) && (serviceProviderBP <= 4000) );
if (balances[msg.sender] >= _value && _value > 0) {
var fee = safeDiv(safeMul(_value, serviceProviderBP), 10000);
var transferredToSeller = safeSub(_value, fee);
balances[_seller] = safeAdd(balances[_seller], transferredToSeller);
Transfer(msg.sender, _seller, transferredToSeller);
return true;
} else {
return false;
}
}
// @param _providerToAdd
// @return success
// @dev Buyer authorizes the Service Provider (to call settleBuyer). For security reason, _providerToAdd needs to be whitelisted by Wolk Foundation first
function authorizeProvider(address _providerToAdd) returns (bool success) {
require(settlers[_providerToAdd]);
authorized[msg.sender][_providerToAdd] = true;
AuthorizeServiceProvider(msg.sender, _providerToAdd);
return true;
}
// @param _providerToRemove
// @return success
// @dev Buyer deauthorizes the Service Provider (from calling settleBuyer)
function deauthorizeProvider(address _providerToRemove) returns (bool success) {
authorized[msg.sender][_providerToRemove] = false;
DeauthorizeServiceProvider(msg.sender, _providerToRemove);
return true;
}
// @param _owner
// @param _serviceProvider
// @return authorizationStatus
// @dev Check authorization between account and Service Provider
function checkAuthorization(address _owner, address _serviceProvider) constant returns (bool authorizationStatus) {
return authorized[_owner][_serviceProvider];
}
// @param _owner
// @param _providerToAdd
// @return authorizationStatus
// @dev Grant authorization between account and Service Provider on buyers' behalf [only accessible by Contract Owner]
// @note Explicit permission from balance owner MUST be obtained beforehand
function grantService(address _owner, address _providerToAdd) onlyOwner returns (bool authorizationStatus) {
var isPreauthorized = authorized[_owner][msg.sender];
if (isPreauthorized && settlers[_providerToAdd] ) {
authorized[_owner][_providerToAdd] = true;
AuthorizeServiceProvider(msg.sender, _providerToAdd);
return true;
}else{
return false;
}
}
// @param _owner
// @param _providerToRemove
// @return authorization_status
// @dev Revoke authorization between account and Service Provider on buyers' behalf [only accessible by Contract Owner]
// @note Explicit permission from balance owner are NOT required for disabling ill-intent Service Provider
function removeService(address _owner, address _providerToRemove) onlyOwner returns (bool authorizationStatus) {
authorized[_owner][_providerToRemove] = false;
DeauthorizeServiceProvider(_owner, _providerToRemove);
return true;
}
}
contract BancorFormula is SafeMath {
// Taken from https://github.com/bancorprotocol/contracts/blob/master/solidity/contracts/BancorFormula.sol
uint8 constant PRECISION = 32; // fractional bits
uint256 constant FIXED_ONE = uint256(1) << PRECISION; // 0x100000000
uint256 constant FIXED_TWO = uint256(2) << PRECISION; // 0x200000000
uint256 constant MAX_VAL = uint256(1) << (256 - PRECISION); // 0x0000000100000000000000000000000000000000000000000000000000000000
/**
@dev given a token supply, reserve, CRR and a deposit amount (in the reserve token), calculates the return for a given change (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 100) - 1)
@param _supply token total supply
@param _reserveBalance total reserve
@param _reserveRatio constant reserve ratio, 1-100
@param _depositAmount deposit amount, in reserve token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _depositAmount) public constant returns (uint256) {
// validate input
require(_supply != 0 && _reserveBalance != 0 && _reserveRatio > 0 && _reserveRatio <= 100);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
uint256 baseN = safeAdd(_depositAmount, _reserveBalance);
uint256 temp;
// special case if the CRR = 100
if (_reserveRatio == 100) {
temp = safeMul(_supply, baseN) / _reserveBalance;
return safeSub(temp, _supply);
}
uint256 resN = power(baseN, _reserveBalance, _reserveRatio, 100);
temp = safeMul(_supply, resN) / FIXED_ONE;
uint256 result = safeSub(temp, _supply);
// from the result, we deduct the minimal increment, which is a
// function of S and precision.
return safeSub(result, _supply / 0x100000000);
}
/**
@dev given a token supply, reserve, CRR and a sell amount (in the main token), calculates the return for a given change (in the reserve token)
Formula:
Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / 100)))
@param _supply token total supply
@param _reserveBalance total reserve
@param _reserveRatio constant reserve ratio, 1-100
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _sellAmount) public constant returns (uint256) {
// validate input
require(_supply != 0 && _reserveBalance != 0 && _reserveRatio > 0 && _reserveRatio <= 100 && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
uint256 baseN = safeSub(_supply, _sellAmount);
uint256 temp1;
uint256 temp2;
// special case if the CRR = 100
if (_reserveRatio == 100) {
temp1 = safeMul(_reserveBalance, _supply);
temp2 = safeMul(_reserveBalance, baseN);
return safeSub(temp1, temp2) / _supply;
}
// special case for selling the entire supply
if (_sellAmount == _supply)
return _reserveBalance;
uint256 resN = power(_supply, baseN, 100, _reserveRatio);
temp1 = safeMul(_reserveBalance, resN);
temp2 = safeMul(_reserveBalance, FIXED_ONE);
uint256 result = safeSub(temp1, temp2) / resN;
// from the result, we deduct the minimal increment, which is a
// function of R and precision.
return safeSub(result, _reserveBalance / 0x100000000);
}
/**
@dev Calculate (_baseN / _baseD) ^ (_expN / _expD)
Returns result upshifted by PRECISION
This method is overflow-safe
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal returns (uint256 resN) {
uint256 logbase = ln(_baseN, _baseD);
// Not using safeDiv here, since safeDiv protects against
// precision loss. It’s unavoidable, however
// Both `ln` and `fixedExp` are overflow-safe.
resN = fixedExp(safeMul(logbase, _expN) / _expD);
return resN;
}
/**
input range:
- numerator: [1, uint256_max >> PRECISION]
- denominator: [1, uint256_max >> PRECISION]
output range:
[0, 0x9b43d4f8d6]
This method asserts outside of bounds
*/
function ln(uint256 _numerator, uint256 _denominator) internal returns (uint256) {
// denominator > numerator: less than one yields negative values. Unsupported
assert(_denominator <= _numerator);
// log(1) is the lowest we can go
assert(_denominator != 0 && _numerator != 0);
// Upper 32 bits are scaled off by PRECISION
assert(_numerator < MAX_VAL);
assert(_denominator < MAX_VAL);
return fixedLoge( (_numerator * FIXED_ONE) / _denominator);
}
/**
input range:
[0x100000000,uint256_max]
output range:
[0, 0x9b43d4f8d6]
This method asserts outside of bounds
*/
function fixedLoge(uint256 _x) internal returns (uint256 logE) {
/*
Since `fixedLog2_min` output range is max `0xdfffffffff`
(40 bits, or 5 bytes), we can use a very large approximation
for `ln(2)`. This one is used since it’s the max accuracy
of Python `ln(2)`
0xb17217f7d1cf78 = ln(2) * (1 << 56)
*/
//Cannot represent negative numbers (below 1)
assert(_x >= FIXED_ONE);
uint256 log2 = fixedLog2(_x);
logE = (log2 * 0xb17217f7d1cf78) >> 56;
}
/**
Returns log2(x >> 32) << 32 [1]
So x is assumed to be already upshifted 32 bits, and
the result is also upshifted 32 bits.
[1] The function returns a number which is lower than the
actual value
input-range :
[0x100000000,uint256_max]
output-range:
[0,0xdfffffffff]
This method asserts outside of bounds
*/
function fixedLog2(uint256 _x) internal returns (uint256) {
// Numbers below 1 are negative.
assert( _x >= FIXED_ONE);
uint256 hi = 0;
while (_x >= FIXED_TWO) {
_x >>= 1;
hi += FIXED_ONE;
}
for (uint8 i = 0; i < PRECISION; ++i) {
_x = (_x * _x) / FIXED_ONE;
if (_x >= FIXED_TWO) {
_x >>= 1;
hi += uint256(1) << (PRECISION - 1 - i);
}
}
return hi;
}
/**
fixedExp is a ‘protected’ version of `fixedExpUnsafe`, which
asserts instead of overflows
*/
function fixedExp(uint256 _x) internal returns (uint256) {
assert(_x <= 0x386bfdba29);
return fixedExpUnsafe(_x);
}
/**
fixedExp
Calculates e^x according to maclauren summation:
e^x = 1+x+x^2/2!...+x^n/n!
and returns e^(x>>32) << 32, that is, upshifted for accuracy
Input range:
- Function ok at <= 242329958953
- Function fails at >= 242329958954
This method is is visible for testcases, but not meant for direct use.
The values in this method been generated via the following python snippet:
def calculateFactorials():
“”"Method to print out the factorials for fixedExp”“”
ni = []
ni.append( 295232799039604140847618609643520000000) # 34!
ITERATIONS = 34
for n in range( 1, ITERATIONS,1 ) :
ni.append(math.floor(ni[n - 1] / n))
print( “\n “.join([“xi = (xi * _x) >> PRECISION;\n res += xi * %s;” % hex(int(x)) for x in ni]))
*/
function fixedExpUnsafe(uint256 _x) internal returns (uint256) {
uint256 xi = FIXED_ONE;
uint256 res = 0xde1bc4d19efcac82445da75b00000000 * xi;
xi = (xi * _x) >> PRECISION;
res += xi * 0xde1bc4d19efcb0000000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x6f0de268cf7e58000000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x2504a0cd9a7f72000000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x9412833669fdc800000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x1d9d4d714865f500000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x4ef8ce836bba8c0000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xb481d807d1aa68000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x16903b00fa354d000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x281cdaac677b3400000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x402e2aad725eb80000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x5d5a6c9f31fe24000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x7c7890d442a83000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x9931ed540345280000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xaf147cf24ce150000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xbac08546b867d000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xbac08546b867d00000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xafc441338061b8000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x9c3cabbc0056e000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x839168328705c80000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x694120286c04a0000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x50319e98b3d2c400;
xi = (xi * _x) >> PRECISION;
res += xi * 0x3a52a1e36b82020;
xi = (xi * _x) >> PRECISION;
res += xi * 0x289286e0fce002;
xi = (xi * _x) >> PRECISION;
res += xi * 0x1b0c59eb53400;
xi = (xi * _x) >> PRECISION;
res += xi * 0x114f95b55400;
xi = (xi * _x) >> PRECISION;
res += xi * 0xaa7210d200;
xi = (xi * _x) >> PRECISION;
res += xi * 0x650139600;
xi = (xi * _x) >> PRECISION;
res += xi * 0x39b78e80;
xi = (xi * _x) >> PRECISION;
res += xi * 0x1fd8080;
xi = (xi * _x) >> PRECISION;
res += xi * 0x10fbc0;
xi = (xi * _x) >> PRECISION;
res += xi * 0x8c40;
xi = (xi * _x) >> PRECISION;
res += xi * 0x462;
xi = (xi * _x) >> PRECISION;
res += xi * 0x22;
return res / 0xde1bc4d19efcac82445da75b00000000;
}
}
contract WolkExchange is WolkProtocol, BancorFormula {
uint256 public maxPerExchangeBP = 50;
// @param _maxPerExchange
// @return success
// @dev Set max sell token amount per transaction -- only Wolk Foundation can set this
function setMaxPerExchange(uint256 _maxPerExchange) onlyOwner returns (bool success) {
require( (_maxPerExchange >= 10) && (_maxPerExchange <= 100) );
maxPerExchangeBP = _maxPerExchange;
return true;
}
// @return Estimated Liquidation Cap
// @dev Liquidation Cap per transaction is used to ensure proper price discovery for Wolk Exchange
function EstLiquidationCap() public constant returns (uint256) {
if (saleCompleted){
var liquidationMax = safeDiv(safeMul(totalTokens, maxPerExchangeBP), 10000);
if (liquidationMax < 100 * 10**decimals){
liquidationMax = 100 * 10**decimals;
}
return liquidationMax;
}else{
return 0;
}
}
// @param _wolkAmount
// @return ethReceivable
// @dev send Wolk into contract in exchange for eth, at an exchange rate based on the Bancor Protocol derivation and decrease totalSupply accordingly
function sellWolk(uint256 _wolkAmount) isTransferable() external returns(uint256) {
uint256 sellCap = EstLiquidationCap();
uint256 ethReceivable = calculateSaleReturn(totalTokens, reserveBalance, percentageETHReserve, _wolkAmount);
require( (sellCap >= _wolkAmount) && (balances[msg.sender] >= _wolkAmount) && (this.balance > ethReceivable) );
balances[msg.sender] = safeSub(balances[msg.sender], _wolkAmount);
totalTokens = safeSub(totalTokens, _wolkAmount);
reserveBalance = safeSub(this.balance, ethReceivable);
WolkDestroyed(msg.sender, _wolkAmount);
msg.sender.transfer(ethReceivable);
return ethReceivable;
}
// @return wolkReceivable
// @dev send eth into contract in exchange for Wolk tokens, at an exchange rate based on the Bancor Protocol derivation and increase totalSupply accordingly
function purchaseWolk() isTransferable() payable external returns(uint256){
uint256 wolkReceivable = calculatePurchaseReturn(totalTokens, reserveBalance, percentageETHReserve, msg.value);
totalTokens = safeAdd(totalTokens, wolkReceivable);
balances[msg.sender] = safeAdd(balances[msg.sender], wolkReceivable);
reserveBalance = safeAdd(reserveBalance, msg.value);
WolkCreated(msg.sender, wolkReceivable);
return wolkReceivable;
}
// @param _exactWolk
// @return ethRefundable
// @dev send eth into contract in exchange for exact amount of Wolk tokens with margin of error of no more than 1 Wolk.
// @note Purchase with the insufficient eth will be cancelled and returned; exceeding eth balanance from purchase, if any, will be returned.
function purchaseExactWolk(uint256 _exactWolk) isTransferable() payable external returns(uint256){
uint256 wolkReceivable = calculatePurchaseReturn(totalTokens, reserveBalance, percentageETHReserve, msg.value);
if (wolkReceivable < _exactWolk){
// Cancel Insufficient Purchase
revert();
return msg.value;
}else {
var wolkDiff = safeSub(wolkReceivable, _exactWolk);
uint256 ethRefundable = 0;
// Refund if wolkDiff exceeds 1 Wolk
if (wolkDiff < 10**decimals){
// Credit Buyer Full amount if within margin of error
totalTokens = safeAdd(totalTokens, wolkReceivable);
balances[msg.sender] = safeAdd(balances[msg.sender], wolkReceivable);
reserveBalance = safeAdd(reserveBalance, msg.value);
WolkCreated(msg.sender, wolkReceivable);
return 0;
}else{
ethRefundable = calculateSaleReturn( safeAdd(totalTokens, wolkReceivable) , safeAdd(reserveBalance, msg.value), percentageETHReserve, wolkDiff);
totalTokens = safeAdd(totalTokens, _exactWolk);
balances[msg.sender] = safeAdd(balances[msg.sender], _exactWolk);
reserveBalance = safeAdd(reserveBalance, safeSub(msg.value, ethRefundable));
WolkCreated(msg.sender, _exactWolk);
msg.sender.transfer(ethRefundable);
return ethRefundable;
}
}
}
}
|
/ denominator > numerator: less than one yields negative values. Unsupported log(1) is the lowest we can go Upper 32 bits are scaled off by PRECISION
|
function ln(uint256 _numerator, uint256 _denominator) internal returns (uint256) {
assert(_denominator <= _numerator);
assert(_denominator != 0 && _numerator != 0);
assert(_numerator < MAX_VAL);
assert(_denominator < MAX_VAL);
return fixedLoge( (_numerator * FIXED_ONE) / _denominator);
}
[0x100000000,uint256_max]
output range:
[0, 0x9b43d4f8d6]
This method asserts outside of bounds
| 6,433,473 |
./partial_match/42/0xC5b06D95aB6146AD5857716BE6c66318381C7Ea9/sources/ERC20.sol
|
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 account, address spender, uint256 amount) internal virtual {
require(account != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[account][spender] = amount;
emit Approval(account, spender, amount);
}
| 8,995,699 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IERC20.sol";
import "./UniswapV2Library.sol";
contract TradeProxyV2 {
address payable immutable private owner;
address payable immutable private weth;
constructor(
address payable _owner,
address payable _weth) {
owner = _owner;
weth = _weth;
}
receive() payable external {}
// debug
// event Swap(uint256 amountIn, uint256 amount0Out, uint256 amount1Out,
// uint256 reserves0, uint256 reserves1, uint256 flag);
// EVENTS
// event BeforeTransfer(uint256 amountIn, uint256 amount0Out, uint256 amount1Out,
// uint256 reserves0, uint256 reserves1, uint256 flag);
// event BeforeSwap();
// 测试uniswap的swap函数
// 花费tknCost,得到tknGet;
function swap(
IUniswapV2Pair pair,
IERC20 costToken,
uint256 amountIn,
uint256 flag // 0 or 1
) private returns (uint256 amountOut) {
uint256[2] memory reserves;
(reserves[0], reserves[1],) = pair.getReserves();
amountOut = UniswapV2Library.getAmountOut(
amountIn, reserves[(flag ^ 0)], reserves[(flag ^ 1)]);
// emit BeforeTransfer(amountIn, flag * amountOut, (1 - flag) * amountOut,
// reserves[0], reserves[1], flag);
// 向pair合约转入amount
costToken.transfer(address(pair), amountIn);
// emit BeforeSwap();
// 将swap出来的token转入到本合约
pair.swap(flag * amountOut, (1 - flag) * amountOut, address(this), new bytes(0));
// debug
// emit Swap(amountIn, flag * amountOut, (1 - flag) * amountOut,
// reserves[0], reserves[1], flag);
}
// 起始token必须是WETH,pairs的第一个pair必须是WETH-xxx
function doTrade(address[] calldata pairs,
address[] calldata costToken,
uint256 costWeth,
uint256 flag) external {
require(msg.sender == owner);
uint256 amountIn = costWeth;
for (uint i = 0; i < pairs.length; ++i) {
amountIn = swap(
IUniswapV2Pair(pairs[i]),
IERC20(costToken[i]),
amountIn,
((flag >> i) & 1));
}
}
// 将套利合约的token转回来
function moneyback(address tokenAddr) external {
require(msg.sender == owner);
// 将所有的token转给owner
IERC20 tkn = IERC20(tokenAddr);
uint balance = tkn.balanceOf(address(this));
tkn.transfer(owner, balance);
}
// 将套利合约的eth转回来
function ethback() external {
require(msg.sender == owner);
// 将所有的eth转给owner
uint balance = address(this).balance;
owner.transfer(balance);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
}
// 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. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* 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;
}
}
}
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;
}
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
|
将套利合约的eth转回来 将所有的eth转给owner
|
function ethback() external {
require(msg.sender == owner);
uint balance = address(this).balance;
owner.transfer(balance);
}
| 9,829,857 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {Pausable} from '@openzeppelin/contracts/security/Pausable.sol';
import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import {MerkleProof} from '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol';
import {IERC20, SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {IStakeFor} from './IStakeFor.sol';
/**
* @title ListingRewardsDistributor
* @notice It distributes X2Y2 tokens with rolling Merkle airdrops.
*/
contract ListingRewardDistributor is Pausable, ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
uint256 public constant BUFFER_ADMIN_WITHDRAW = 3 days;
IERC20 public immutable x2y2Token;
IStakeFor public stakingPool;
// Current reward round (users can only claim pending rewards for the current round)
uint256 public currentRewardRound;
// Last paused timestamp
uint256 public lastPausedTimestamp;
// Max amount per user in current tree
uint256 public maximumAmountPerUserInCurrentTree;
// Total amount claimed by user (in X2Y2)
mapping(address => uint256) public amountClaimedByUser;
// Merkle root for a reward round
mapping(uint256 => bytes32) public merkleRootOfRewardRound;
// Checks whether a merkle root was used
mapping(bytes32 => bool) public merkleRootUsed;
// Keeps track on whether user has claimed at a given reward round
mapping(uint256 => mapping(address => bool)) public hasUserClaimedForRewardRound;
event RewardsClaim(address indexed user, uint256 indexed rewardRound, uint256 amount);
event UpdateListingRewards(uint256 indexed rewardRound);
event TokenWithdrawnOwner(uint256 amount);
event StakingPoolUpdate(address newPool);
/**
* @notice Constructor
* @param _x2y2Token address of the X2Y2 token
*/
constructor(IERC20 _x2y2Token, IStakeFor _stakingPool) {
x2y2Token = _x2y2Token;
stakingPool = _stakingPool;
_pause();
}
function updateStakingPool(IStakeFor _stakingPool) external onlyOwner {
stakingPool = _stakingPool;
emit StakingPoolUpdate(address(_stakingPool));
}
/**
* @notice Claim pending rewards
* @param amount amount to claim
* @param staking direct staking
* @param merkleProof array containing the merkle proof
*/
function claim(
uint256 amount,
bool staking,
bytes32[] calldata merkleProof
) external whenNotPaused nonReentrant {
// Verify the reward round is not claimed already
require(
!hasUserClaimedForRewardRound[currentRewardRound][msg.sender],
'Rewards: Already claimed'
);
(bool claimStatus, uint256 adjustedAmount) = _canClaim(msg.sender, amount, merkleProof);
require(claimStatus, 'Rewards: Invalid proof');
require(maximumAmountPerUserInCurrentTree >= amount, 'Rewards: Amount higher than max');
// Set mapping for user and round as true
hasUserClaimedForRewardRound[currentRewardRound][msg.sender] = true;
// Adjust amount claimed
amountClaimedByUser[msg.sender] += adjustedAmount;
// Stake/transfer adjusted amount
if (staking) {
require(address(stakingPool) != address(0), 'Cannot stake to address(0)');
x2y2Token.approve(address(stakingPool), amount);
stakingPool.depositFor(msg.sender, adjustedAmount);
} else {
x2y2Token.safeTransfer(msg.sender, adjustedAmount);
}
emit RewardsClaim(msg.sender, currentRewardRound, adjustedAmount);
}
/**
* @notice Update trading rewards with a new merkle root
* @dev It automatically increments the currentRewardRound
* @param merkleRoot root of the computed merkle tree
*/
function updateListingRewards(bytes32 merkleRoot, uint256 newMaximumAmountPerUser)
external
onlyOwner
{
require(!merkleRootUsed[merkleRoot], 'Owner: Merkle root already used');
currentRewardRound++;
merkleRootOfRewardRound[currentRewardRound] = merkleRoot;
merkleRootUsed[merkleRoot] = true;
maximumAmountPerUserInCurrentTree = newMaximumAmountPerUser;
emit UpdateListingRewards(currentRewardRound);
}
/**
* @notice Pause distribution
*/
function pauseDistribution() external onlyOwner whenNotPaused {
lastPausedTimestamp = block.timestamp;
_pause();
}
/**
* @notice Unpause distribution
*/
function unpauseDistribution() external onlyOwner whenPaused {
_unpause();
}
/**
* @notice Transfer X2Y2 tokens back to owner
* @dev It is for emergency purposes
* @param amount amount to withdraw
*/
function withdrawTokenRewards(uint256 amount) external onlyOwner whenPaused {
require(
block.timestamp > (lastPausedTimestamp + BUFFER_ADMIN_WITHDRAW),
'Owner: Too early to withdraw'
);
x2y2Token.safeTransfer(msg.sender, amount);
emit TokenWithdrawnOwner(amount);
}
/**
* @notice Check whether it is possible to claim and how much based on previous distribution
* @param user address of the user
* @param amount amount to claim
* @param merkleProof array with the merkle proof
*/
function canClaim(
address user,
uint256 amount,
bytes32[] calldata merkleProof
) external view returns (bool, uint256) {
return _canClaim(user, amount, merkleProof);
}
/**
* @notice Check whether it is possible to claim and how much based on previous distribution
* @param user address of the user
* @param amount amount to claim
* @param merkleProof array with the merkle proof
*/
function _canClaim(
address user,
uint256 amount,
bytes32[] calldata merkleProof
) internal view returns (bool, uint256) {
// Compute the node and verify the merkle proof
bytes32 node = keccak256(abi.encodePacked(user, amount));
bool canUserClaim = MerkleProof.verify(
merkleProof,
merkleRootOfRewardRound[currentRewardRound],
node
);
if ((!canUserClaim) || (hasUserClaimedForRewardRound[currentRewardRound][user])) {
return (false, 0);
} else {
return (true, amount - amountClaimedByUser[user]);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
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) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IStakeFor {
function depositFor(address user, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
}
}
}
|
Update trading rewards with a new merkle root It automatically increments the currentRewardRound merkleRoot root of the computed merkle tree/
|
function updateListingRewards(bytes32 merkleRoot, uint256 newMaximumAmountPerUser)
external
onlyOwner
{
require(!merkleRootUsed[merkleRoot], 'Owner: Merkle root already used');
currentRewardRound++;
merkleRootOfRewardRound[currentRewardRound] = merkleRoot;
merkleRootUsed[merkleRoot] = true;
maximumAmountPerUserInCurrentTree = newMaximumAmountPerUser;
emit UpdateListingRewards(currentRewardRound);
}
| 328,443 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./AccountManager.sol";
import "./DocManager.sol";
import "./SaveDocToken.sol";
import "./SaveDocStruct.sol";
/**
* @title SAV Doc
* @notice Contract used to secure, transfer, share and certify document
* @dev Main contract of SAV Doc
*/
contract SaveDoc is Ownable, SaveDocStruct
{
mapping(address => mapping(uint256 => CertificationRequest)) private requests;
SaveDocToken private saveDocToken;
DocManager private docManager;
AccountManager private accountManager;
/**
* @dev Create new Sav Doc contract
* @param _docManager address of DocManager contract
* @param _saveDocToken address of SaveDocToken contract
* @param _accountManager address of AccountManager contract
*/
constructor(DocManager _docManager, SaveDocToken _saveDocToken, AccountManager _accountManager)
{
docManager = _docManager;
saveDocToken = _saveDocToken;
accountManager = _accountManager;
}
event Subscribe(address newUser, string name, string pubkey);
event SubscribeAuthority(address newUser, string pubkey);
event ChangeUsername(address user, string newUsername);
event Unsubcribe(address user);
event SecureDocument(address user, uint256 tokenID);
event DeleteDocumment(address ownerDoc, uint256 tokenID, bool forTransfer);
event TransferDocument(address from, address to, uint256 tokenID);
event ShareDoc(address from, address to, uint256 tokenID);
event AcceptTransferDoc(address newOwner, uint256 tokenID);
event DeleteMyDocCopy(address ownerDoc, uint256 tokenID);
event RequestCertification(address applicant, uint256 tokenID);
event AcceptCertificationRequest(address certifying, address applicant, uint256 tokenID, bool keepCopy);
event RejectCertificationRequest(address certifying, address applicant, uint256 tokenID);
/**
* @dev modifier to check if token is owned by sender
* @param tokenID ID of token
*/
modifier isMyToken(uint256 tokenID)
{
require(saveDocToken.ownerOf(tokenID) == msg.sender, "SaveDoc: Cet NFT ne vous appartient pas !");
_;
}
/**
* @dev modifier to check if user exists
* @param addressUser address of user
*/
modifier userExist(address addressUser)
{
require(accountManager.checkIfUserExist(addressUser), "SaveDoc: Cette utilisateur n'existe pas.");
_;
}
/**
* @dev modifier to check if `_certifying` already receive a certification request
* @param _certifying _certifying of document
* @param _tokenID ID of token
*/
modifier requestExist(address _certifying, uint256 _tokenID)
{
require(requests[_certifying][_tokenID].exist, "SavDoc: La demande de certification n'existe pas.");
_;
}
/**
* @dev modifier to check if `_certifying` not already receive a certification request
* @param _certifying _certifying of document
* @param _tokenID ID of token
*/
modifier requestNotExist(address _certifying, uint256 _tokenID)
{
require(!requests[_certifying][_tokenID].exist, "SavDoc: La demande de certification existe.");
_;
}
/**
* @notice Subscribe to SAV Doc as user
* @dev Create new user (emits a Subscribe event)
* @param name name of user
* @param pubKey public key of user
* @param passwordMaster password master of user
*/
function subscribe(string memory name, string memory pubKey, string memory passwordMaster) external
{
accountManager.addUser(msg.sender, name, pubKey, passwordMaster);
emit Subscribe(msg.sender, name, pubKey);
}
/**
* @dev Create new authority (emits a SubscribeAuthority event)
* @param authority address of authority
* @param name name of authority
* @param pubKey public key of authority
* @param passwordMaster password master of authority
*/
function subscribeAuthority(address authority,string memory name, string memory pubKey, string memory passwordMaster) onlyOwner() external
{
accountManager.addAuthority(authority, name, pubKey, passwordMaster);
emit SubscribeAuthority(authority, pubKey);
}
/**
* @notice View my informations
* @dev Get sender user informations
* @return user informations
*/
function viewMyProfil() view external userExist(msg.sender) returns(User memory)
{
return accountManager.getUser(msg.sender);
}
/**
* @notice View informations of user by address
* @dev Get informations of user
* @param _address address of user
* @return user informations of `address`
*/
function viewProfil(address _address) view external returns(User memory)
{
return accountManager.getUser(_address);
}
/**
* @notice Get my password master
* @dev Get password master of sender
* @return password master of sender
*/
function getMyPasswordMaster() view external returns(string memory)
{
return accountManager.getPasswordMaster(msg.sender);
}
/**
* @notice Set my name
* @dev Set user name of sender (emits a ChangeUsername event)
* @param name new name of user
*/
function changeMyName(string memory name) external
{
accountManager.setUser(msg.sender, name);
emit ChangeUsername(msg.sender, name);
}
/**
* @notice Delete my account
* @dev Remove account of sender (emits a Unsubcribe event)
*/
function unsubscribe() external userExist(msg.sender)
{
docManager.deleteAllDocs(msg.sender);
docManager.delAllCopyDoc(msg.sender);
accountManager.delUser(msg.sender);
emit Unsubcribe(msg.sender);
}
/**
* @notice Secure a document
* @dev Secure a document (emits a SecureDocument event)
* @param tokenName name of document
* @param tokenURI URI of token
* @param tokenMime mime type of document
* @param tokenLength size (in bytes) of document
* @param filePath folder of document
* @param passwordEncrypted encrypted password of document
* @param hashNFT hash of document
* @return secured document informations
*/
function secureDocument(string memory tokenName, string memory tokenURI, string memory tokenMime, uint256 tokenLength, string memory filePath, string memory passwordEncrypted, string memory hashNFT) external userExist(msg.sender) returns (Document memory)
{
uint256 tokenID;
Document memory document;
tokenID = saveDocToken.mint(msg.sender, tokenURI);
document = docManager.createDoc(msg.sender, tokenID, tokenName, tokenMime, tokenLength, filePath, passwordEncrypted, hashNFT);
emit SecureDocument(msg.sender, tokenID);
return document;
}
/**
* @notice Delete a secured document by tokenID
* @dev Delete a secured document of sender by tokenID (see _delMyDocument function) (emits a DeleteDocumment event)
* @param tokenID ID of token
* @param forTransfer true to burn token
*/
function delMyDocument(uint256 tokenID, bool forTransfer) external isMyToken(tokenID)
{
_delMyDocument(msg.sender, tokenID, forTransfer);
}
/**
* @dev Delete a secured document of `ownerDoc` by tokenID (emits a DeleteDocumment event)
* @param ownerDoc owner of document
* @param tokenID ID of token
* @param forTransfer true to burn token
*/
function _delMyDocument(address ownerDoc, uint256 tokenID, bool forTransfer) private
{
docManager.deleteDoc(ownerDoc, tokenID);
if (!forTransfer)
{
saveDocToken.burn(tokenID, ownerDoc);
}
emit DeleteDocumment(ownerDoc, tokenID, forTransfer);
}
/**
* @notice Get token URI of document
* @dev Get token URI of document
* @param tokenID ID of token
* @return token URI of document
*/
function getTokenURI(uint256 tokenID) external view isMyToken(tokenID) returns(string memory)
{
return saveDocToken.tokenURI(tokenID);
}
/**
* @notice Transfer my secured document
* @dev Transfer a secured document (emits a TransferDocument event)
* @param to recipient of document
* @param tokenID ID of token
* @param tokenURITmp token URI to make the document visible by `to`
*/
function transferDoc(address to, uint256 tokenID, string memory tokenURITmp) external isMyToken(tokenID) userExist(to)
{
docManager.createCopyDoc(msg.sender, to, tokenID, tokenURITmp, TypeDoc.CopyPendingTransfer);
saveDocToken.transfer(msg.sender, to, tokenID);
_delMyDocument(msg.sender, tokenID, true);
emit TransferDocument(msg.sender, to, tokenID);
}
/**
* @notice Share my secured document
* @dev Share a secured document (emits a ShareDoc event)
* @param tokenID ID of token
* @param to recipient of document
* @param tokenURI token URI to make the document visible by `to`
*/
function shareDoc(uint256 tokenID, address to, string memory tokenURI) external isMyToken(tokenID) userExist(to)
{
docManager.createCopyDoc(msg.sender, to, tokenID, tokenURI, TypeDoc.CopyShared);
emit ShareDoc(msg.sender, to, tokenID);
}
/**
* @notice Accept a transfered document
* @dev Accept a transfered document (emits a AcceptTransferDoc event)
* @param tokenID ID of token
* @param newTokenURI URI of token
* @param passwordEncrypted encrypted password of document
*/
function acceptNewDoc(uint256 tokenID, string memory newTokenURI, string memory passwordEncrypted) external isMyToken(tokenID)
{
docManager.convertTypeDoc(msg.sender, TypeDoc.CopyPendingTransfer, TypeDoc.Original, tokenID, passwordEncrypted);
saveDocToken.setTokenURI(tokenID, newTokenURI, msg.sender);
emit AcceptTransferDoc(msg.sender, tokenID);
}
/**
* @notice Delete a shared document
* @dev Delete a shared document (emits a DeleteMyDocCopy event)
* @param tokenID ID of token
*/
function delCopyDocShared(uint tokenID) external
{
int256 index = docManager.getIndexNFT(msg.sender, TypeDoc.CopyShared, tokenID);
require(index > -1, "SaveDoc: Vous n'avez pas de copie a supprimer");
docManager.delCopyDoc(msg.sender, TypeDoc.CopyShared, uint256(index));
emit DeleteMyDocCopy(msg.sender, tokenID);
}
/**
* @notice Send nex certification request
* @dev Send nex certification request (emits a RequestCertification event)
* @param _tokenID ID of document
* @param _tokenURI URI of document
* @param _certifying recipent of request
*/
function requestCertification(uint256 _tokenID, string memory _tokenURI, address _certifying) isMyToken(_tokenID) external userExist(_certifying) requestNotExist(_certifying, _tokenID)
{
docManager.createCopyDoc(msg.sender, _certifying, _tokenID, _tokenURI, TypeDoc.CopyCertified);
requests[_certifying][_tokenID].applicant = msg.sender;
requests[_certifying][_tokenID].tokenID = _tokenID;
requests[_certifying][_tokenID].exist = true;
emit RequestCertification(requests[_certifying][_tokenID].applicant, requests[_certifying][_tokenID].tokenID);
}
/**
* @notice View all my secured documents
* @dev get all secured document of sender
* @return secured documents
*/
function viewMyDocs() view external userExist(msg.sender) returns(Document[] memory)
{
return docManager.getDocs(msg.sender);
}
/**
* @notice View all my shared documents
* @dev get all shared document of sender
* @return shared documents
*/
function viewMyCopyDocs() view external userExist(msg.sender) returns(Document[] memory)
{
return docManager.getAllCopyShared(msg.sender);
}
/**
* @notice View all my documents being transferred
* @dev get all documents being transferred of sender
* @return documents being transferred
*/
function viewDocPendingTransfer() view external userExist(msg.sender) returns(Document[] memory)
{
return docManager.getAllCopyPendingTransfer(msg.sender);
}
/**
* @notice View all my certified documents
* @dev get all certified document of sender
* @return certified documents
*/
function viewDocCertified() view external userExist(msg.sender) returns(Document[] memory)
{
return docManager.getAllCopyCertified(msg.sender);
}
/**
* @notice View one of all certification requests of document
* @dev Get certification request of document by token ID
* @param _tokenID ID of token
* @return certification request
*/
function viewCertificationRequest(uint256 _tokenID) requestExist(msg.sender, _tokenID) view external returns(CertificationRequest memory)
{
return requests[msg.sender][_tokenID];
}
/**
* @dev Delete certification request
* @param _certifying certifying of document
* @param _tokenID ID of token
*/
function delRequest(address _certifying, uint256 _tokenID) private
{
delete requests[_certifying][_tokenID];
}
/**
* @dev Certify a document
* @param applicant owner of document
* @param tokenID ID of token
* @param hashNFT hash of document
*/
function certifyDocument(address applicant, uint256 tokenID, string memory hashNFT) private
{
bool isAuthority;
isAuthority = accountManager.isAuthority(msg.sender);
docManager.certify(msg.sender, isAuthority, applicant, tokenID, hashNFT);
}
/**
* @notice Accept a certification request
* @dev Accept a certification request (emits a AcceptCertificationRequest event)
* @param _tokenID ID of token
* @param _hashNFT hash of document
* @param _keepCopyDoc true if sender want to keep a copy of document
*/
function acceptCertificationRequest(uint256 _tokenID, string memory _hashNFT, bool _keepCopyDoc) requestExist(msg.sender, _tokenID) userExist(msg.sender) public
{
CertificationRequest memory request = requests[msg.sender][_tokenID];
int256 index = docManager.getIndexNFT(msg.sender, TypeDoc.CopyCertified, request.tokenID);
certifyDocument(request.applicant, request.tokenID, _hashNFT);
delRequest(msg.sender, request.tokenID);
if (_keepCopyDoc) {
docManager.convertTypeDoc(msg.sender, TypeDoc.CopyCertified, TypeDoc.CopyShared, request.tokenID, "");
} else {
docManager.delCopyDoc(msg.sender, TypeDoc.CopyCertified, uint256(index));
}
emit AcceptCertificationRequest(msg.sender, request.applicant, request.tokenID, _keepCopyDoc);
}
/**
* @notice Reject a certification request
* @dev Reject a certification request (emits a RejectCertificationRequest event)
* @param _tokenID ID of token
*/
function rejectCertificationRequest(uint256 _tokenID) requestExist(msg.sender, _tokenID) external
{
CertificationRequest memory request = requests[msg.sender][_tokenID];
int256 index = docManager.getIndexNFT(msg.sender, TypeDoc.CopyCertified, request.tokenID);
delRequest(msg.sender, _tokenID);
docManager.delCopyDoc(msg.sender, TypeDoc.CopyCertified, uint256(index));
emit RejectCertificationRequest(msg.sender, request.applicant, request.tokenID);
}
/**
* @notice Check if token exist
* @dev Check if token exist
* @param tokenID ID of token
* @return true if token exists
*/
function tokenExist(uint256 tokenID) view onlyOwner() public returns(bool)
{
return saveDocToken.exist(tokenID);
}
}
|
Share my secured document Share a secured document (emits a ShareDoc event) tokenID ID of token to recipient of document tokenURI token URI to make the document visible by `to`/
|
function shareDoc(uint256 tokenID, address to, string memory tokenURI) external isMyToken(tokenID) userExist(to)
{
docManager.createCopyDoc(msg.sender, to, tokenID, tokenURI, TypeDoc.CopyShared);
emit ShareDoc(msg.sender, to, tokenID);
}
| 13,069,010 |
pragma solidity ^0.6.0;
import "../token/ZIPI.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/GSN/GSNRecipientSignature.sol";
contract DemoDapp is GSNRecipientSignatureUpgradeSafe {
/**
* @dev Example dapp function: spend a base token from the basket.
*/
function spendBaseToken() external returns (bool) {
ZIPI zip = ZIPI(address(0)); // Replace 0 address with ZIP address
zip.transfer(address(this), 100); // Send 100 ZIP to dapp
// Send 100 ZIP worth of FET to this dapp's Etch contract
zip.redeem("FET", 100, "0xTHISDAPPCONTRACTFETCHADDRESS");
return true;
}
/**
* @dev GSN: accept relayed call.
*/
function acceptRelayedCall(
address relay,
address from,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory approvalData,
uint256 maxPossibleCharge
) public override view returns (uint256, bytes memory) {
return _approveRelayedCall();
}
/**
* @dev GSN: preprocessing for relayed calls.
*/
function _preRelayedCall(bytes memory context) internal override returns (bytes32) {
}
/**
* @dev GSN: postprocessing for relayed calls.
*/
function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) internal override {
}
}
|
GSN: preprocessing for relayed calls./
|
function _preRelayedCall(bytes memory context) internal override returns (bytes32) {
}
| 5,463,989 |
/**
* https://github.com/drlecks/Ethereum-Contracts/tree/master/Hodl
*/
pragma solidity ^0.4.23;
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
//How many decimals to show.
uint256 public decimals;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @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 `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens 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);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract OwnableContract {
address superOwner;
constructor() public {
superOwner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == superOwner);
_;
}
function viewSuperOwner() public view returns (address owner) {
return superOwner;
}
function changeOwner(address newOwner) onlyOwner public {
superOwner = newOwner;
}
}
contract BlockableContract is OwnableContract{
bool public blockedContract;
constructor() public {
blockedContract = false;
}
modifier contractActive() {
require(!blockedContract);
_;
}
function doBlockContract() onlyOwner public {
blockedContract = true;
}
function unBlockContract() onlyOwner public {
blockedContract = false;
}
}
contract Hodl is BlockableContract{
struct Safe{
uint256 id;
address user;
address tokenAddress;
uint256 amount;
uint256 time;
}
/**
* @dev safes variables
*/
mapping( address => uint256[]) public _userSafes;
mapping( uint256 => Safe) private _safes;
uint256 private _currentIndex;
mapping( address => uint256) public _totalSaved;
/**
* @dev owner variables
*/
uint256 public comission; //0..100
mapping( address => uint256) private _systemReserves;
address[] public _listedReserves;
/**
* constructor
*/
constructor() public {
_currentIndex = 1;
comission = 10;
}
/**
* fallback function to receive donation eth
*/
function () public payable {
require(msg.value>0);
_systemReserves[0x0] = add(_systemReserves[0x0], msg.value);
}
/**
* how many safes has the user
*/
function GetUserSafesLength(address a) public view returns (uint256 length) {
return _userSafes[a].length;
}
/**
* how many tokens are reservedfor owner as comission
*/
function GetReserveAmount(address tokenAddress) public view returns (uint256 amount){
return _systemReserves[tokenAddress];
}
/**
* returns safe's values'
*/
function Getsafe(uint256 _id) public view
returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 time)
{
Safe storage s = _safes[_id];
return(s.id, s.user, s.tokenAddress, s.amount, s.time);
}
/**
* add new hodl safe (ETH)
*/
function HodlEth(uint256 time) public contractActive payable {
require(msg.value > 0);
require(time>now);
_userSafes[msg.sender].push(_currentIndex);
_safes[_currentIndex] = Safe(_currentIndex, msg.sender, 0x0, msg.value, time);
_totalSaved[0x0] = add(_totalSaved[0x0], msg.value);
_currentIndex++;
}
/**
* add new hodl safe (ERC20 token)
*/
function ClaimHodlToken(address tokenAddress, uint256 amount, uint256 time) public contractActive {
require(tokenAddress != 0x0);
require(amount>0);
require(time>now);
EIP20Interface token = EIP20Interface(tokenAddress);
require( token.transferFrom(msg.sender, address(this), amount) );
_userSafes[msg.sender].push(_currentIndex);
_safes[_currentIndex] = Safe(_currentIndex, msg.sender, tokenAddress, amount, time);
_totalSaved[tokenAddress] = add(_totalSaved[tokenAddress], amount);
_currentIndex++;
}
/**
* user, claim back a hodl safe
*/
function UserRetireHodl(uint256 id) public {
Safe storage s = _safes[id];
require(s.id != 0);
require(s.user == msg.sender);
RetireHodl(id);
}
/**
* private retire hodl safe action
*/
function RetireHodl(uint256 id) private {
Safe storage s = _safes[id];
require(s.id != 0);
if(s.time < now) //hodl complete
{
if(s.tokenAddress == 0x0)
PayEth(s.user, s.amount);
else
PayToken(s.user, s.tokenAddress, s.amount);
}
else //hodl in progress
{
uint256 realComission = mul(s.amount, comission) / 100;
uint256 realAmount = sub(s.amount, realComission);
if(s.tokenAddress == 0x0)
PayEth(s.user, realAmount);
else
PayToken(s.user, s.tokenAddress, realAmount);
StoreComission(s.tokenAddress, realComission);
}
DeleteSafe(s);
}
/**
* private pay eth to address
*/
function PayEth(address user, uint256 amount) private {
require(address(this).balance >= amount);
user.transfer(amount);
}
/**
* private pay token to address
*/
function PayToken(address user, address tokenAddress, uint256 amount) private{
EIP20Interface token = EIP20Interface(tokenAddress);
require(token.balanceOf(address(this)) >= amount);
token.transfer(user, amount);
}
/**
* store comission from unfinished hodl
*/
function StoreComission(address tokenAddress, uint256 amount) private {
_systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], amount);
bool isNew = true;
for(uint256 i = 0; i < _listedReserves.length; i++) {
if(_listedReserves[i] == tokenAddress) {
isNew = false;
break;
}
}
if(isNew) _listedReserves.push(tokenAddress);
}
/**
* delete safe values in storage
*/
function DeleteSafe(Safe s) private {
_totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], s.amount);
delete _safes[s.id];
uint256[] storage vector = _userSafes[msg.sender];
uint256 size = vector.length;
for(uint256 i = 0; i < size; i++) {
if(vector[i] == s.id) {
vector[i] = vector[size-1];
vector.length--;
break;
}
}
}
//OWNER
/**
* owner retire hodl safe
*/
function OwnerRetireHodl(uint256 id) public onlyOwner {
Safe storage s = _safes[id];
require(s.id != 0);
RetireHodl(id);
}
/**
* owner, change comission value
*/
function ChangeComission(uint256 newComission) onlyOwner public {
comission = newComission;
}
/**
* owner withdraw eth reserved from comissions
*/
function WithdrawReserve(address tokenAddress) onlyOwner public
{
require(_systemReserves[tokenAddress] > 0);
uint256 amount = _systemReserves[tokenAddress];
_systemReserves[tokenAddress] = 0;
EIP20Interface token = EIP20Interface(tokenAddress);
require(token.balanceOf(address(this)) >= amount);
token.transfer(msg.sender, amount);
}
/**
* owner withdraw token reserved from comission
*/
function WithdrawAllReserves() onlyOwner public {
//eth
uint256 x = _systemReserves[0x0];
if(x > 0 && x <= address(this).balance) {
_systemReserves[0x0] = 0;
msg.sender.transfer( _systemReserves[0x0] );
}
//tokens
address ta;
EIP20Interface token;
for(uint256 i = 0; i < _listedReserves.length; i++) {
ta = _listedReserves[i];
if(_systemReserves[ta] > 0)
{
x = _systemReserves[ta];
_systemReserves[ta] = 0;
token = EIP20Interface(ta);
token.transfer(msg.sender, x);
}
}
_listedReserves.length = 0;
}
/**
* owner remove free eth
*/
function WithdrawSpecialEth(uint256 amount) onlyOwner public
{
require(amount > 0);
uint256 freeBalance = address(this).balance - _totalSaved[0x0];
require(freeBalance >= amount);
msg.sender.transfer(amount);
}
/**
* owner remove free token
*/
function WithdrawSpecialToken(address tokenAddress, uint256 amount) onlyOwner public
{
EIP20Interface token = EIP20Interface(tokenAddress);
uint256 freeBalance = token.balanceOf(address(this)) - _totalSaved[tokenAddress];
require(freeBalance >= amount);
token.transfer(msg.sender, amount);
}
//AUX
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
|
private pay token to address/
|
function PayToken(address user, address tokenAddress, uint256 amount) private{
EIP20Interface token = EIP20Interface(tokenAddress);
require(token.balanceOf(address(this)) >= amount);
token.transfer(user, amount);
}
| 13,474,269 |
./full_match/137/0x767724fC7C77F6AaC4f30B6271290cf93eFd5B52/sources/contracts/RadiantAINexus.sol
|
Implement your token transfer logic here This function should transfer the specified amount of RadiantAI tokens to the given address
|
function transferTokens(address to, uint256 amount) internal {
}
| 3,764,609 |
pragma solidity =0.6.6;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract UniswapV2Router02 is IUniswapV2Router02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IUniswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, 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 virtual override returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
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(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'92558fe898fb93529ed6e2b5245e428bb9e22a2f329a13aefdeda833baf0aa70' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
|
ADD LIQUIDITY create the pair if it doesn't exist yet
|
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
| 156,764 |
./full_match/1/0x167860391dd8C6B11ce4Fb37458F65E87c2ec863/sources/browser/NIFITYWORLD.sol
|
Deposit LP tokens to Contract for nifity allocation.
|
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accNifityPerShare).div(1e12).sub(user.rewardDebt);
safeNifityTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accNifityPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 3,199,041 |
pragma solidity ^0.4.11;
contract ChronoBankPlatform {
mapping(bytes32 => address) public proxies;
function symbols(uint _idx) public constant returns (bytes32);
function symbolsCount() public constant returns (uint);
function name(bytes32 _symbol) returns(string);
function setProxy(address _address, bytes32 _symbol) returns(uint errorCode);
function isCreated(bytes32 _symbol) constant returns(bool);
function isOwner(address _owner, bytes32 _symbol) returns(bool);
function owner(bytes32 _symbol) constant returns(address);
function totalSupply(bytes32 _symbol) returns(uint);
function balanceOf(address _holder, bytes32 _symbol) returns(uint);
function allowance(address _from, address _spender, bytes32 _symbol) returns(uint);
function baseUnit(bytes32 _symbol) returns(uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) returns(uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) returns(uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) returns(uint errorCode);
function isReissuable(bytes32 _symbol) returns(bool);
function changeOwnership(bytes32 _symbol, address _newOwner) returns(uint errorCode);
}
contract ChronoBankAsset {
function __transferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function __approve(address _spender, uint _value, address _sender) returns(bool);
function __process(bytes _data, address _sender) payable {
revert();
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
/**
* @title ChronoBank Asset Proxy.
*
* Proxy implements ERC20 interface and acts as a gateway to a single platform asset.
* Proxy adds symbol and caller(sender) when forwarding requests to platform.
* Every request that is made by caller first sent to the specific asset implementation
* contract, which then calls back to be forwarded onto platform.
*
* Calls flow: Caller ->
* Proxy.func(...) ->
* Asset.__func(..., Caller.address) ->
* Proxy.__func(..., Caller.address) ->
* Platform.proxyFunc(..., symbol, Caller.address)
*
* Asset implementation contract is mutable, but each user have an option to stick with
* old implementation, through explicit decision made in timely manner, if he doesn't agree
* with new rules.
* Each user have a possibility to upgrade to latest asset contract implementation, without the
* possibility to rollback.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract ChronoBankAssetProxy is ERC20 {
// Supports ChronoBankPlatform ability to return error codes from methods
uint constant OK = 1;
// Assigned platform, immutable.
ChronoBankPlatform public chronoBankPlatform;
// Assigned symbol, immutable.
bytes32 public smbl;
// Assigned name, immutable.
string public name;
string public symbol;
/**
* Sets platform address, assigns symbol and name.
*
* Can be set only once.
*
* @param _chronoBankPlatform platform contract address.
* @param _symbol assigned symbol.
* @param _name assigned name.
*
* @return success.
*/
function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) returns(bool) {
if (address(chronoBankPlatform) != 0x0) {
return false;
}
chronoBankPlatform = _chronoBankPlatform;
symbol = _symbol;
smbl = stringToBytes32(_symbol);
name = _name;
return true;
}
function stringToBytes32(string memory source) returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
/**
* Only platform is allowed to call.
*/
modifier onlyChronoBankPlatform() {
if (msg.sender == address(chronoBankPlatform)) {
_;
}
}
/**
* Only current asset owner is allowed to call.
*/
modifier onlyAssetOwner() {
if (chronoBankPlatform.isOwner(msg.sender, smbl)) {
_;
}
}
/**
* Returns asset implementation contract for current caller.
*
* @return asset implementation contract.
*/
function _getAsset() internal returns(ChronoBankAsset) {
return ChronoBankAsset(getVersionFor(msg.sender));
}
/**
* Returns asset total supply.
*
* @return asset total supply.
*/
function totalSupply() constant returns(uint) {
return chronoBankPlatform.totalSupply(smbl);
}
/**
* Returns asset balance for a particular holder.
*
* @param _owner holder address.
*
* @return holder balance.
*/
function balanceOf(address _owner) constant returns(uint) {
return chronoBankPlatform.balanceOf(_owner, smbl);
}
/**
* Returns asset allowance from one holder to another.
*
* @param _from holder that allowed spending.
* @param _spender holder that is allowed to spend.
*
* @return holder to spender allowance.
*/
function allowance(address _from, address _spender) constant returns(uint) {
return chronoBankPlatform.allowance(_from, _spender, smbl);
}
/**
* Returns asset decimals.
*
* @return asset decimals.
*/
function decimals() constant returns(uint8) {
return chronoBankPlatform.baseUnit(smbl);
}
/**
* Transfers asset balance from the caller to specified receiver.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transfer(address _to, uint _value) returns(bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
/**
* Transfers asset balance from the caller to specified receiver adding specified comment.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
*
* @return success.
*/
function transferWithReference(address _to, uint _value, string _reference) returns(bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, _reference);
}
else {
return false;
}
}
/**
* Resolves asset implementation contract for the caller and forwards there arguments along with
* the caller address.
*
* @return success.
*/
function _transferWithReference(address _to, uint _value, string _reference) internal returns(bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
/**
* Performs transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) {
return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK;
}
/**
* Prforms allowance transfer of asset balance between holders.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transferFrom(address _from, address _to, uint _value) returns(bool) {
if (_to != 0x0) {
return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) {
return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
*
* @return success.
*/
function approve(address _spender, uint _value) returns(bool) {
if (_spender != 0x0) {
return _getAsset().__approve(_spender, _value, msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance setting call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
* @param _sender initial caller.
*
* @return success.
*/
function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) returns(bool) {
return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK;
}
/**
* Emits ERC20 Transfer event on this contract.
*
* Can only be, and, called by assigned platform when asset transfer happens.
*/
function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform() {
Transfer(_from, _to, _value);
}
/**
* Emits ERC20 Approval event on this contract.
*
* Can only be, and, called by assigned platform when asset allowance set happens.
*/
function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform() {
Approval(_from, _spender, _value);
}
/**
* Resolves asset implementation contract for the caller and forwards there transaction data,
* along with the value. This allows for proxy interface growth.
*/
function () payable {
_getAsset().__process.value(msg.value)(msg.data, msg.sender);
}
/**
* Indicates an upgrade freeze-time start, and the next asset implementation contract.
*/
event UpgradeProposal(address newVersion);
// Current asset implementation contract address.
address latestVersion;
// Proposed next asset implementation contract address.
address pendingVersion;
// Upgrade freeze-time start.
uint pendingVersionTimestamp;
// Timespan for users to review the new implementation and make decision.
uint constant UPGRADE_FREEZE_TIME = 3 days;
// Asset implementation contract address that user decided to stick with.
// 0x0 means that user uses latest version.
mapping(address => address) userOptOutVersion;
/**
* Only asset implementation contract assigned to sender is allowed to call.
*/
modifier onlyAccess(address _sender) {
if (getVersionFor(_sender) == msg.sender) {
_;
}
}
/**
* Returns asset implementation contract address assigned to sender.
*
* @param _sender sender address.
*
* @return asset implementation contract address.
*/
function getVersionFor(address _sender) constant returns(address) {
return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender];
}
/**
* Returns current asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getLatestVersion() constant returns(address) {
return latestVersion;
}
/**
* Returns proposed next asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getPendingVersion() constant returns(address) {
return pendingVersion;
}
/**
* Returns upgrade freeze-time start.
*
* @return freeze-time start.
*/
function getPendingVersionTimestamp() constant returns(uint) {
return pendingVersionTimestamp;
}
/**
* Propose next asset implementation contract address.
*
* Can only be called by current asset owner.
*
* Note: freeze-time should not be applied for the initial setup.
*
* @param _newVersion asset implementation contract address.
*
* @return success.
*/
function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) {
// Should not already be in the upgrading process.
if (pendingVersion != 0x0) {
return false;
}
// New version address should be other than 0x0.
if (_newVersion == 0x0) {
return false;
}
// Don't apply freeze-time for the initial setup.
if (latestVersion == 0x0) {
latestVersion = _newVersion;
return true;
}
pendingVersion = _newVersion;
pendingVersionTimestamp = now;
UpgradeProposal(_newVersion);
return true;
}
/**
* Cancel the pending upgrade process.
*
* Can only be called by current asset owner.
*
* @return success.
*/
function purgeUpgrade() onlyAssetOwner() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
/**
* Finalize an upgrade process setting new asset implementation contract address.
*
* Can only be called after an upgrade freeze-time.
*
* @return success.
*/
function commitUpgrade() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) {
return false;
}
latestVersion = pendingVersion;
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
/**
* Disagree with proposed upgrade, and stick with current asset implementation
* until further explicit agreement to upgrade.
*
* @return success.
*/
function optOut() returns(bool) {
if (userOptOutVersion[msg.sender] != 0x0) {
return false;
}
userOptOutVersion[msg.sender] = latestVersion;
return true;
}
/**
* Implicitly agree to upgrade to current and future asset implementation upgrades,
* until further explicit disagreement.
*
* @return success.
*/
function optIn() returns(bool) {
delete userOptOutVersion[msg.sender];
return true;
}
}
|
Returns asset decimals. return asset decimals./
|
function decimals() constant returns(uint8) {
return chronoBankPlatform.baseUnit(smbl);
}
| 15,415,237 |
./full_match/137/0x0908498eFE5b3f80e4fC42Edab7C271496A52096/sources/JAave_1JunPolDev.sol
|
transfer ethers in this contract to fees collector contract _amount ethers amount to be transferred/
|
function withdrawEthToFeesCollector(uint256 _amount) external onlyAdmins {
TransferETHHelper.safeTransferETH(feesCollectorAddress, _amount);
}
| 4,687,132 |
/**
*Submitted for verification at Etherscan.io on 2021-06-09
*/
pragma solidity ^0.6.12;
// SPDX-License-Identifier: UNLICENCED
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
interface ERC721Basic is ERC165 {
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) external view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) external view returns (address _owner);
function exists(uint256 _tokenId) external view returns (bool _exists);
function approve(address _to, uint256 _tokenId) external;
function getApproved(uint256 _tokenId)
external view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) external;
function isApprovedForAll(address _owner, address _operator)
external view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
external;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
external;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
// bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes memory _data
) external returns(bytes4);
}
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0);
c = a / b;
}
function max(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a <= b ? a : b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b != 0);
c = a % b;
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
override
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
interface IERC721Enumerable is ERC721Basic {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/*
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/*
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
// 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;
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/*
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view override 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 override returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/*
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view override returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) override public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view override returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) override 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
override
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
override
{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
override
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
override
public
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) virtual internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) virtual internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) virtual 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) virtual internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address payable public owner;
address public newOwner;
bool private initialised;
event OwnershipTransferred(address indexed from, address indexed to);
function initOwned(address _owner) internal {
require(!initialised);
owner = address(uint160(_owner));
initialised = true;
}
function transferOwnership(address _newOwner) public {
require(msg.sender == owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = address(uint160(newOwner));
newOwner = address(0);
}
modifier onlyOwner() {
require(owner == msg.sender, "Owned: caller is not the owner");
_;
}
}
contract MyERC721Metadata is ERC165, ERC721BasicToken, Owned {
// Token name
string private _name;
// Token symbol
string private _symbol;
uint256 public _max_supply;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
string public baseURI = "http://api.lianstreets.com/nft/tokenId/";
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol, uint256 maxSupply) public {
initOwned(msg.sender);
_name = name;
_symbol = symbol;
_max_supply = maxSupply;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
function uintToBytes(uint256 num) internal pure returns (bytes memory b) {
if (num == 0) {
b = new bytes(1);
b[0] = byte(uint8(48));
} else {
uint256 j = num;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
b = new bytes(length);
uint k = length - 1;
while (num != 0) {
b[k--] = byte(uint8(48 + num % 10));
num /= 10;
}
}
}
function setBaseURI(string memory uri) public onlyOwner {
baseURI = uri;
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
function maxSupply() external view returns (uint256) {
return _max_supply;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory url = _tokenURIs[tokenId];
bytes memory urlAsBytes = bytes(url);
if (urlAsBytes.length == 0) {
bytes memory baseURIAsBytes = bytes(baseURI);
bytes memory tokenIdAsBytes = uintToBytes(tokenId);
bytes memory b = new bytes(baseURIAsBytes.length + tokenIdAsBytes.length);
uint256 i;
uint256 j;
for (i = 0; i < baseURIAsBytes.length; i++) {
b[j++] = baseURIAsBytes[i];
}
for (i = 0; i < tokenIdAsBytes.length; i++) {
b[j++] = tokenIdAsBytes[i];
}
return string(b);
} else {
return _tokenURIs[tokenId];
}
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) override internal {
super._burn(owner,tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// ----------------------------------------------------------------------------
// Secondary Accounts Data Structure
// ----------------------------------------------------------------------------
library Accounts {
struct Account {
uint timestamp;
uint index;
address account;
}
struct Data {
bool initialised;
mapping(address => Account) entries;
address[] index;
}
event AccountAdded(address owner, address account, uint totalAfter);
event AccountRemoved(address owner, address account, uint totalAfter);
function init(Data storage self) internal {
require(!self.initialised);
self.initialised = true;
}
function hasKey(Data storage self, address account) internal view returns (bool) {
return self.entries[account].timestamp > 0;
}
function add(Data storage self, address owner, address account) internal {
require(self.entries[account].timestamp == 0);
self.index.push(account);
self.entries[account] = Account(block.timestamp, self.index.length - 1, account);
emit AccountAdded(owner, account, self.index.length);
}
function remove(Data storage self, address owner, address account) internal {
require(self.entries[account].timestamp > 0);
uint removeIndex = self.entries[account].index;
emit AccountRemoved(owner, account, self.index.length - 1);
uint lastIndex = self.index.length - 1;
address lastIndexKey = self.index[lastIndex];
self.index[removeIndex] = lastIndexKey;
self.entries[lastIndexKey].index = removeIndex;
delete self.entries[account];
if (self.index.length > 0) {
self.index.pop();
}
}
function removeAll(Data storage self, address owner) internal {
if (self.initialised) {
while (self.index.length > 0) {
uint lastIndex = self.index.length - 1;
address lastIndexKey = self.index[lastIndex];
emit AccountRemoved(owner, lastIndexKey, lastIndex);
delete self.entries[lastIndexKey];
self.index.pop();
}
}
}
function length(Data storage self) internal view returns (uint) {
return self.index.length;
}
}
// ----------------------------------------------------------------------------
// Attributes Data Structure
// ----------------------------------------------------------------------------
library Attributes {
struct Value {
uint timestamp;
uint index;
string value;
}
struct Data {
bool initialised;
mapping(string => Value) entries;
string[] index;
}
event AttributeAdded(uint256 indexed tokenId, string key, string value, uint totalAfter);
event AttributeRemoved(uint256 indexed tokenId, string key, uint totalAfter);
event AttributeUpdated(uint256 indexed tokenId, string key, string value);
function init(Data storage self) internal {
require(!self.initialised);
self.initialised = true;
}
function hasKey(Data storage self, string memory key) internal view returns (bool) {
return self.entries[key].timestamp > 0;
}
function add(Data storage self, uint256 tokenId, string memory key, string memory value) internal {
require(self.entries[key].timestamp == 0);
self.index.push(key);
self.entries[key] = Value(block.timestamp, self.index.length - 1, value);
emit AttributeAdded(tokenId, key, value, self.index.length);
}
function remove(Data storage self, uint256 tokenId, string memory key) internal {
require(self.entries[key].timestamp > 0);
uint removeIndex = self.entries[key].index;
emit AttributeRemoved(tokenId, key, self.index.length - 1);
uint lastIndex = self.index.length - 1;
string memory lastIndexKey = self.index[lastIndex];
self.index[removeIndex] = lastIndexKey;
self.entries[lastIndexKey].index = removeIndex;
delete self.entries[key];
if (self.index.length > 0) {
self.index.pop();
}
}
function removeAll(Data storage self, uint256 tokenId) internal {
if (self.initialised) {
while (self.index.length > 0) {
uint lastIndex = self.index.length - 1;
string memory lastIndexKey = self.index[lastIndex];
emit AttributeRemoved(tokenId, lastIndexKey, lastIndex);
delete self.entries[lastIndexKey];
self.index.pop();
}
}
}
function setValue(Data storage self, uint256 tokenId, string memory key, string memory value) internal {
Value storage _value = self.entries[key];
require(_value.timestamp > 0);
_value.timestamp = block.timestamp;
emit AttributeUpdated(tokenId, key, value);
_value.value = value;
}
function length(Data storage self) internal view returns (uint) {
return self.index.length;
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
contract LWNFTContract is MyERC721Metadata,IERC721Enumerable {
using Attributes for Attributes.Data;
using Attributes for Attributes.Value;
using Counters for Counters.Counter;
using Accounts for Accounts.Data;
using Accounts for Accounts.Account;
string public constant TYPE_KEY = "type";
string public constant SUBTYPE_KEY = "subtype";
string public constant NAME_KEY = "name";
string public constant DESCRIPTION_KEY = "description";
string public constant TAGS_KEY = "tags";
mapping(uint256 => Attributes.Data) private attributesByTokenIds;
Counters.Counter private _tokenIds;
mapping(address => Accounts.Data) private secondaryAccounts;
// Duplicated from Attributes for NFT contract ABI to contain events
event AttributeAdded(uint256 indexed tokenId, string key, string value, uint totalAfter);
event AttributeRemoved(uint256 indexed tokenId, string key, uint totalAfter);
event AttributeUpdated(uint256 indexed tokenId, string key, string value);
event AccountAdded(address owner, address account, uint totalAfter);
event AccountRemoved(address owner, address account, uint totalAfter);
constructor() MyERC721Metadata("LianWan", "LWNFT",10000000) public {
}
// Mint and burn
/**
* @dev Mint token
*
* @param _to address of token owner
*/
function mint(address _to,uint256 amount) public returns (uint256) {
require(_tokenIds.current() + amount < _max_supply, "DreamChannelNFT: maximum quantity reached");
require(amount > 0, "You must buy at least one .");
require(amount < 200, "DreamChannelNFT: less than 200");
uint256 newTokenId = 1;
for (uint256 i = 0; i < amount; i++) {
_tokenIds.increment();
newTokenId = _tokenIds.current();
_mint(_to, newTokenId);
Attributes.Data storage attributes = attributesByTokenIds[newTokenId];
attributes.init();
}
return newTokenId;
}
function burn(uint256 tokenId) public {
_burn(msg.sender, tokenId);
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
if (attributes.initialised) {
attributes.removeAll(tokenId);
delete attributesByTokenIds[tokenId];
}
}
// Attributes
function numberOfAttributes(uint256 tokenId) public view returns (uint) {
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
if (!attributes.initialised) {
return 0;
} else {
return attributes.length();
}
}
function getKey(uint256 tokenId, uint _index) public view returns (string memory) {
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
if (attributes.initialised) {
if (_index < attributes.index.length) {
return attributes.index[_index];
}
}
return "";
}
function getValue(uint256 tokenId, string memory key) public view returns (uint _exists, uint _index, string memory _value) {
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
if (!attributes.initialised) {
return (0, 0, "");
} else {
Attributes.Value memory attribute = attributes.entries[key];
return (attribute.timestamp, attribute.index, attribute.value);
}
}
function getAttributeByIndex(uint256 tokenId, uint256 _index) public view returns (string memory _key, string memory _value, uint timestamp) {
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
if (attributes.initialised) {
if (_index < attributes.index.length) {
string memory key = attributes.index[_index];
bytes memory keyInBytes = bytes(key);
if (keyInBytes.length > 0) {
Attributes.Value memory attribute = attributes.entries[key];
return (key, attribute.value, attribute.timestamp);
}
}
}
return ("", "", 0);
}
function addAttribute(uint256 tokenId, string memory key, string memory value) public {
require(isOwnerOf(tokenId, msg.sender), "DreamChannelNFT: add attribute of token that is not own");
require(keccak256(abi.encodePacked(key)) != keccak256(abi.encodePacked(TYPE_KEY)));
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
if (!attributes.initialised) {
attributes.init();
}
require(attributes.entries[key].timestamp == 0);
attributes.add(tokenId, key, value);
}
function setAttribute(uint256 tokenId, string memory key, string memory value) public {
require(isOwnerOf(tokenId, msg.sender), "DreamChannelNFT: set attribute of token that is not own");
require(keccak256(abi.encodePacked(key)) != keccak256(abi.encodePacked(TYPE_KEY)));
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
if (!attributes.initialised) {
attributes.init();
}
if (attributes.entries[key].timestamp > 0) {
attributes.setValue(tokenId, key, value);
} else {
attributes.add(tokenId, key, value);
}
}
function removeAttribute(uint256 tokenId, string memory key) public {
require(isOwnerOf(tokenId, msg.sender), "DreamChannelNFT: remove attribute of token that is not own");
require(keccak256(abi.encodePacked(key)) != keccak256(abi.encodePacked(TYPE_KEY)));
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
require(attributes.initialised);
attributes.remove(tokenId, key);
}
function updateAttribute(uint256 tokenId, string memory key, string memory value) public {
require(isOwnerOf(tokenId, msg.sender), "DreamChannelNFT: update attribute of token that is not own");
require(keccak256(abi.encodePacked(key)) != keccak256(abi.encodePacked(TYPE_KEY)));
Attributes.Data storage attributes = attributesByTokenIds[tokenId];
require(attributes.initialised);
require(attributes.entries[key].timestamp > 0);
attributes.setValue(tokenId, key, value);
}
function isOwnerOf(uint tokenId, address account) public view returns (bool) {
address owner = ownerOf(tokenId);
if (owner == account) {
return true;
} else {
Accounts.Data storage accounts = secondaryAccounts[owner];
if (accounts.initialised) {
if (accounts.hasKey(account)) {
return true;
}
}
}
return false;
}
function addSecondaryAccount(address account) public {
require(account != address(0), "DreamChannelNFT: cannot add null secondary account");
Accounts.Data storage accounts = secondaryAccounts[msg.sender];
if (!accounts.initialised) {
accounts.init();
}
require(accounts.entries[account].timestamp == 0);
accounts.add(msg.sender, account);
}
function removeSecondaryAccount(address account) public {
require(account != address(0), "DreamChannelNFT: cannot remove null secondary account");
Accounts.Data storage accounts = secondaryAccounts[msg.sender];
require(accounts.initialised);
accounts.remove(msg.sender, account);
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) public{
require(isOwnerOf(tokenId, msg.sender), "DreamChannelNFT: set Token URI of token that is not own");
_setTokenURI(tokenId, _tokenURI);
}
/**
* @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 _tokenIds.current();
}
}
|
Gets the approved address for a token ID, or zero if no address set _tokenId uint256 ID of the token to query the approval of return address currently approved for the given token ID/
|
function getApproved(uint256 _tokenId) public view override returns (address) {
return tokenApprovals[_tokenId];
}
| 1,151,605 |
./partial_match/42/0x0dAAe03aaEe84B5c5BeBD3B0f8ccb539C1A5463E/sources/FeePool.sol
|
Send the fees to claiming address. account The address to send the fees to. pUSDAmount The amount of fees priced in pUSD./ Grab the pUSD Pynth NOTE: we do not control the FEE_ADDRESS so it is not possible to do an ERC20.approve() transaction to allow this feePool to call ERC20.transferFrom to the accounts address Burn the source amount Mint their new pynths
|
function _payFees(address account, uint pUSDAmount) internal notFeeAddress(account) {
IPynth pUSDPynth = issuer().pynths(pUSD);
pUSDPynth.burn(FEE_ADDRESS, pUSDAmount);
pUSDPynth.issue(account, pUSDAmount);
}
| 3,330,608 |
pragma solidity ^0.4.21;
import '../math/SafeMath.sol';
import '../token/IERC20Token.sol';
/**
* @title BasePoll
* @dev Abstract base class for polling contracts
*/
contract BasePoll is SafeMath {
struct Vote {
uint256 time;
uint256 weight;
bool agree;
}
uint256 public constant MAX_TOKENS_WEIGHT_DENOM = 1000;
IERC20Token public token;
address public fundAddress;
uint256 public startTime;
uint256 public endTime;
bool checkTransfersAfterEnd;
uint256 public yesCounter = 0;
uint256 public noCounter = 0;
uint256 public totalVoted = 0;
bool public finalized;
mapping(address => Vote) public votesByAddress;
modifier checkTime() {
require(now >= startTime && now <= endTime);
_;
}
modifier notFinalized() {
require(!finalized);
_;
}
/**
* @dev BasePoll constructor
* @param _tokenAddress ERC20 compatible token contract address
* @param _fundAddress Fund contract address
* @param _startTime Poll start time
* @param _endTime Poll end time
*/
constructor(address _tokenAddress, address _fundAddress, uint256 _startTime, uint256 _endTime, bool _checkTransfersAfterEnd) public {
require(_tokenAddress != address(0));
require(_startTime >= now && _endTime > _startTime);
token = IERC20Token(_tokenAddress);
fundAddress = _fundAddress;
startTime = _startTime;
endTime = _endTime;
finalized = false;
checkTransfersAfterEnd = _checkTransfersAfterEnd;
}
/**
* @dev Process user`s vote
* @param agree True if user endorses the proposal else False
*/
function vote(bool agree) public checkTime {
require(votesByAddress[msg.sender].time == 0);
uint256 voiceWeight = token.balanceOf(msg.sender);
uint256 maxVoiceWeight = safeDiv(token.totalSupply(), MAX_TOKENS_WEIGHT_DENOM);
voiceWeight = voiceWeight <= maxVoiceWeight ? voiceWeight : maxVoiceWeight;
if(agree) {
yesCounter = safeAdd(yesCounter, voiceWeight);
} else {
noCounter = safeAdd(noCounter, voiceWeight);
}
votesByAddress[msg.sender].time = now;
votesByAddress[msg.sender].weight = voiceWeight;
votesByAddress[msg.sender].agree = agree;
totalVoted = safeAdd(totalVoted, 1);
}
/**
* @dev Revoke user`s vote
*/
function revokeVote() public checkTime {
require(votesByAddress[msg.sender].time > 0);
uint256 voiceWeight = votesByAddress[msg.sender].weight;
bool agree = votesByAddress[msg.sender].agree;
votesByAddress[msg.sender].time = 0;
votesByAddress[msg.sender].weight = 0;
votesByAddress[msg.sender].agree = false;
totalVoted = safeSub(totalVoted, 1);
if(agree) {
yesCounter = safeSub(yesCounter, voiceWeight);
} else {
noCounter = safeSub(noCounter, voiceWeight);
}
}
/**
* @dev Function is called after token transfer from user`s wallet to check and correct user`s vote
*
*/
function onTokenTransfer(address tokenHolder, uint256 amount) public {
require(msg.sender == fundAddress);
if(votesByAddress[tokenHolder].time == 0) {
return;
}
if(!checkTransfersAfterEnd) {
if(finalized || (now < startTime || now > endTime)) {
return;
}
}
if(token.balanceOf(tokenHolder) >= votesByAddress[tokenHolder].weight) {
return;
}
uint256 voiceWeight = amount;
if(amount > votesByAddress[tokenHolder].weight) {
voiceWeight = votesByAddress[tokenHolder].weight;
}
if(votesByAddress[tokenHolder].agree) {
yesCounter = safeSub(yesCounter, voiceWeight);
} else {
noCounter = safeSub(noCounter, voiceWeight);
}
votesByAddress[tokenHolder].weight = safeSub(votesByAddress[tokenHolder].weight, voiceWeight);
}
/**
* Finalize poll and call onPollFinish callback with result
*/
function tryToFinalize() public notFinalized returns(bool) {
if(now < endTime) {
return false;
}
finalized = true;
onPollFinish(isSubjectApproved());
return true;
}
function isNowApproved() public view returns(bool) {
return isSubjectApproved();
}
function isSubjectApproved() internal view returns(bool) {
return yesCounter > noCounter;
}
/**
* @dev callback called after poll finalization
*/
function onPollFinish(bool agree) internal;
}
|
Finalize poll and call onPollFinish callback with result/
|
function tryToFinalize() public notFinalized returns(bool) {
if(now < endTime) {
return false;
}
finalized = true;
onPollFinish(isSubjectApproved());
return true;
}
| 7,281,194 |
pragma solidity ^0.5.1;
/**
* @title Vrenelium Token - VRE
* @author Vrenelium AG 2018/2019
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title SafeMath
*
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Basic token
*
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 token implementation
*
* @dev Implementation of the ERC20 token.
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token with logarithmic approximation to token cap
*/
contract MintableTokenWithCap is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
uint256 public constant TOTAL_TOKEN_CAP = 78000000 * 10 ** 18; // Maximum amount of tokens
uint256 public constant PRE_MINTED_TOKEN_CAP = 24100000 * 10 ** 18; // Amount of pre minted tokens
uint256 public constant PRE_MINTING_END = 1577750400; // x1 - 2019-12-31T00:00:00+00:00 - Pre minting end Timestamp
uint256 public constant MINTING_END = 3187295999; // x2 - 2070-12-31T23:59:59+00:00 - Minting end Timestamp
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
public
returns (bool)
{
require(totalSupply_ + _amount <= getCurrentMintingLimit());
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function getCurrentMintingLimit()
public
view
returns(uint256)
{
if(now <= PRE_MINTING_END) {
return PRE_MINTED_TOKEN_CAP;
}
else if(now <= MINTING_END) {
// Logarithmic approximation until MINTING_END
// qfactor = (ln(2x + 0.2) - ln(0.2)) / (ln(2.2)-ln(0.2))
// Pre calculated values are used for efficiency reasons
if(now <= 1609459199) { // 12/31/2020 @ 11:59pm (UTC)
return 28132170 *10 ** 18;
}
else if(now <= 1640995199) { // 12/31/2021 @ 11:59pm (UTC)
return 31541205 *10 ** 18;
}
else if(now <= 1672531199) { // 12/31/2022 @ 11:59pm (UTC)
return 34500660 *10 ** 18;
}
else if(now <= 1704067199) { // 12/31/2023 @ 11:59pm (UTC)
return 37115417 *10 ** 18;
}
else if(now <= 1735603199) { // 12/31/2024 @ 11:59pm (UTC)
return 39457461 *10 ** 18;
}
else if(now <= 1767225599) { // 12/31/2025 @ 11:59pm (UTC)
return 41583887 *10 ** 18;
}
else if(now <= 1798761599) { // 12/31/2026 @ 11:59pm (UTC)
return 43521339 *10 ** 18;
}
else if(now <= 1830297599) { // 12/31/2027 @ 11:59pm (UTC)
return 45304967 *10 ** 18;
}
else if(now <= 1861919999) { // 12/31/2028 @ 11:59pm (UTC)
return 46961775 *10 ** 18;
}
else if(now <= 1893455999) { // 12/31/2029 @ 11:59pm (UTC)
return 48500727 *10 ** 18;
}
else if(now <= 1924991999) { // 12/31/2030 @ 11:59pm (UTC)
return 49941032 *10 ** 18;
}
else if(now <= 1956527999) { // 12/31/2031 @ 11:59pm (UTC)
return 51294580 *10 ** 18;
}
else if(now <= 1988150399) { // 12/31/2032 @ 11:59pm (UTC)
return 52574631 *10 ** 18;
}
else if(now <= 2019686399) { // 12/31/2033 @ 11:59pm (UTC)
return 53782475 *10 ** 18;
}
else if(now <= 2051222399) { // 12/31/2034 @ 11:59pm (UTC)
return 54928714 *10 ** 18;
}
else if(now <= 2082758399) { // 12/31/2035 @ 11:59pm (UTC)
return 56019326 *10 ** 18;
}
else if(now <= 2114380799) { // 12/31/2036 @ 11:59pm (UTC)
return 57062248 *10 ** 18;
}
else if(now <= 2145916799) { // 12/31/2037 @ 11:59pm (UTC)
return 58056255 *10 ** 18;
}
else if(now <= 2177452799) { // 12/31/2038 @ 11:59pm (UTC)
return 59008160 *10 ** 18;
}
else if(now <= 2208988799) { // 12/31/2039 @ 11:59pm (UTC)
return 59921387 *10 ** 18;
}
else if(now <= 2240611199) { // 12/31/2040 @ 11:59pm (UTC)
return 60801313 *10 ** 18;
}
else if(now <= 2272147199) { // 12/31/2041 @ 11:59pm (UTC)
return 61645817 *10 ** 18;
}
else if(now <= 2303683199) { // 12/31/2042 @ 11:59pm (UTC)
return 62459738 *10 ** 18;
}
else if(now <= 2335219199) { // 12/31/2043 @ 11:59pm (UTC)
return 63245214 *10 ** 18;
}
else if(now <= 2366841599) { // 12/31/2044 @ 11:59pm (UTC)
return 64006212 *10 ** 18;
}
else if(now <= 2398377599) { // 12/31/2045 @ 11:59pm (UTC)
return 64740308 *10 ** 18;
}
else if(now <= 2429913599) { // 12/31/2046 @ 11:59pm (UTC)
return 65451186 *10 ** 18;
}
else if(now <= 2461449599) { // 12/31/2047 @ 11:59pm (UTC)
return 66140270 *10 ** 18;
}
else if(now <= 2493071999) { // 12/31/2048 @ 11:59pm (UTC)
return 66810661 *10 ** 18;
}
else if(now <= 2524607999) { // 12/31/2049 @ 11:59pm (UTC)
return 67459883 *10 ** 18;
}
else if(now <= 2556143999) { // 12/31/2050 @ 11:59pm (UTC)
return 68090879 *10 ** 18;
}
else if(now <= 2587679999) { // 12/31/2051 @ 11:59pm (UTC)
return 68704644 *10 ** 18;
}
else if(now <= 2619302399) { // 12/31/2052 @ 11:59pm (UTC)
return 69303710 *10 ** 18;
}
else if(now <= 2650838399) { // 12/31/2053 @ 11:59pm (UTC)
return 69885650 *10 ** 18;
}
else if(now <= 2682374399) { // 12/31/2054 @ 11:59pm (UTC)
return 70452903 *10 ** 18;
}
else if(now <= 2713910399) { // 12/31/2055 @ 11:59pm (UTC)
return 71006193 *10 ** 18;
}
else if(now <= 2745532799) { // 12/31/2056 @ 11:59pm (UTC)
return 71547652 *10 ** 18;
}
else if(now <= 2777068799) { // 12/31/2057 @ 11:59pm (UTC)
return 72074946 *10 ** 18;
}
else if(now <= 2808604799) { // 12/31/2058 @ 11:59pm (UTC)
return 72590155 *10 ** 18;
}
else if(now <= 2840140799) { // 12/31/2059 @ 11:59pm (UTC)
return 73093818 *10 ** 18;
}
else if(now <= 2871763199) { // 12/31/2060 @ 11:59pm (UTC)
return 73587778 *10 ** 18;
}
else if(now <= 2903299199) { // 12/31/2061 @ 11:59pm (UTC)
return 74069809 *10 ** 18;
}
else if(now <= 2934835199) { // 12/31/2062 @ 11:59pm (UTC)
return 74541721 *10 ** 18;
}
else if(now <= 2966371199) { // 12/31/2063 @ 11:59pm (UTC)
return 75003928 *10 ** 18;
}
else if(now <= 2997993599) { // 12/31/2064 @ 11:59pm (UTC)
return 75458050 *10 ** 18;
}
else if(now <= 3029529599) { // 12/31/2065 @ 11:59pm (UTC)
return 75901975 *10 ** 18;
}
else if(now <= 3061065599) { // 12/31/2066 @ 11:59pm (UTC)
return 76337302 *10 ** 18;
}
else if(now <= 3092601599) { // 12/31/2067 @ 11:59pm (UTC)
return 76764358 *10 ** 18;
}
else if(now <= 3124223999) { // 12/31/2068 @ 11:59pm (UTC)
return 77184590 *10 ** 18;
}
else if(now <= 3155759999) { // 12/31/2069 @ 11:59pm (UTC)
return 77595992 *10 ** 18;
}
else if(now <= 3187295999) { // 12/31/2070 @ 11:59pm (UTC)
return 78000000 *10 ** 18;
}
}
else {
return TOTAL_TOKEN_CAP;
}
}
}
/**
* @title Vrenelium Token Smart Contract
*/
contract VreneliumToken is MintableTokenWithCap {
// Public Constants
string public constant name = "Vrenelium Token";
string public constant symbol = "VRE";
uint8 public constant decimals = 18;
/**
* @dev Modifier to not allow transfers
* to this contract
*/
modifier validDestination(address _to) {
require(_to != address(this));
_;
}
constructor() public {
}
function transferFrom(address _from, address _to, uint256 _value) public
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public
returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval (address _spender, uint _addedValue) public
returns (bool) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval (address _spender, uint _subtractedValue) public
returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue);
}
function transfer(address _to, uint256 _value) public
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
}
|
Logarithmic approximation until MINTING_END qfactor = (ln(2x + 0.2) - ln(0.2)) / (ln(2.2)-ln(0.2)) Pre calculated values are used for efficiency reasons
|
function getCurrentMintingLimit()
public
view
returns(uint256)
{
if(now <= PRE_MINTING_END) {
return PRE_MINTED_TOKEN_CAP;
}
else if(now <= MINTING_END) {
return 28132170 *10 ** 18;
}
return 31541205 *10 ** 18;
}
return 34500660 *10 ** 18;
| 6,473,267 |
/**
*
*
* O~~~ O~~~~~~ O~~ O~~ O~~
* O~~ O~~ O~~ O~~ O~~
* O~~ O~~ O~~ O~~ O~~ O~~ O~~ O~~ O~~ O~~ O~~~~ O~~
* O~~ O~~ O~~ O~~ O~~ O~ O~~ O~~ O~~ O~~~~~~ O~~ O~~ O~~ O~~ O~ O~
* O~~ O~~ O~~O~O~~ O~~~~~ O~~ O~~ O~~ O~~ O~~O~~ O~~ O~~~ O~~ O~~
* O~~ O~~ O~~ O~~ O~~ O~ O~~ O~~ O~~ O~~O~~ O~~ O~~ O~ O~~
* O~~ O~~ O~~ O~~ O~~~~ O~~~ O~~ O~~ O~~ O~~ O~~~ O~~O~~ O~~ O~~
*
*
*
* Generative on-chain NFT series
* Jonathan Chomko, 2021
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/utils/Counters.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
// /**
// * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
// * @dev See https://eips.ethereum.org/EIPS/eip-721
// */
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs - not used with on-chain
// 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");
// return json from folder
return string(abi.encodePacked(baseURI(), tokenId.toString(), '.json'));
}
//Return contract metadata for opensea view
function contractURI() public pure returns (string memory) {
//put something here!
string memory json = Base64.encode(bytes(string(abi.encodePacked('{ "name": "Token Hash","description": "Abstract on-chain generative NFT series.", "external_link": "https://tokenhash.jonathanchomko.com/","seller_fee_basis_points": 1000, "fee_recipient": "0x8490b3dFba40B784e3a16974377c70a139306CFA" } ' ))));
string memory output = string(abi.encodePacked('data:application/json;base64,', json));
// return string(abi.encodePacked(baseURI(), "contract_metadata", '.json'));
return output;
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
// if (bytes(_tokenURIs[tokenId]).length != 0) {
// delete _tokenURIs[tokenId];
// }
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
// function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
// require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
// _tokenURIs[tokenId] = _tokenURI;
// }
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: contracts/ColourTime721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev {ERC721} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - token ID and URI autogeneration
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract TokenHash721 is Context, ERC721, Ownable {
// using Counters for Counters.Counter;
using SafeMath for uint256;
address payable public withdrawalAddress;
//Token sale control logic
// Counters.Counter private piecesSold;
uint256 public maxNumberOfPieces;
//Standard sale
bool public standardSaleActive;
uint256 public pricePerPiece;
//Presale
bool public preSaleActive;
mapping (address => uint256) public whitelisted;
mapping (address => uint256) public preSaleMinted;
event Purchase(address buyer, uint256 price, uint256 tokenId);
event MetadataUpdated(string newTokenUriBase);
constructor(
uint256 givenPricePerPiece,
address payable givenWithdrawalAddress
) ERC721("Token Hash", "TH") {
pricePerPiece = givenPricePerPiece;
withdrawalAddress = givenWithdrawalAddress;
maxNumberOfPieces = 1000;
_setBaseURI("");
}
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function generateHash(uint256 tokenId) internal pure returns (uint256){
return random(string(abi.encodePacked("RANDOM", toString(tokenId)))) % 999;
}
function checkSimilarity(uint256 tokenId, uint256 hashMod) private pure returns(uint256){
uint256 similarity = 0;
//modulo will return 0 even if no digit is present, so we exclude 0
if(tokenId % 10 == hashMod %10 && tokenId % 10 > 0 && hashMod % 10 > 0){
similarity ++;
}
if(tokenId % 100 /10 == hashMod % 100 /10 && tokenId % 100 /10 > 0 && hashMod % 100 /10 > 0){
similarity ++;
}
if(tokenId % 1000 /100 == hashMod % 1000 /100 && tokenId % 1000 /100 > 0 && hashMod % 1000 /100 > 0){
similarity ++;
}
if(tokenId == hashMod){
similarity ++;
}
return similarity;
}
function checkSymmetry(uint256 tokenId, uint256 hashMod) private pure returns(uint256){
uint256 symmetry = 0;
//Hash first and last
if(hashMod % 10 == hashMod % 1000 /100 && hashMod % 10 > 0 && hashMod % 1000 /100 > 0){
symmetry ++;
}
//Hash first and second
if(hashMod % 10 == hashMod % 100 /10 && hashMod % 10 > 0 && hashMod % 100 /10 > 0){
symmetry ++;
}
//Hash second and third
if(hashMod % 100/10 == hashMod % 1000 /100 && hashMod % 100/10 > 0 && hashMod % 1000 /100 > 0){
symmetry ++;
}
//Token ID first and last
if(tokenId % 10 == tokenId % 1000 /100 && tokenId % 10 > 0 && tokenId % 1000 /100 > 0){
symmetry ++;
}
//Token Id first and second
if(tokenId % 10 == tokenId % 100 /10 && tokenId % 10 > 0 && tokenId % 100 /10 > 0){
symmetry ++;
}
//Token Id second and third
if(tokenId % 100/10 == tokenId % 1000 /100 && tokenId % 100/10 > 0 && tokenId % 1000 /100 > 0){
symmetry ++;
}
//Cross - first tokenID to last hash
if(tokenId % 10 == hashMod % 1000 /100 && tokenId % 10 > 0 && hashMod % 1000 /100 > 0){
symmetry ++;
}
//Cross - last token ID to first hash
if(tokenId % 1000 /100 == hashMod % 10 && tokenId % 1000 /100 > 0 && hashMod % 10 > 0){
symmetry ++;
}
//Middle to middle
if(tokenId % 100 /10 == hashMod % 100 /10 && tokenId % 100 /10 > 0 && hashMod % 100 /10 > 0){
symmetry ++;
}
return symmetry;
}
//Generate svg
function tokenURI(uint256 tokenId) override public view returns (string memory){
require(_exists(tokenId) || msg.sender == owner(), "ERC721Metadata: URI query for nonexistent token");
uint256 hashMod = generateHash(tokenId);
if(tokenId == 0x45){
hashMod = 0x1A4;
}
if(tokenId == 0x1A4){
hashMod = 0x45;
}
uint256 similarity = checkSimilarity(tokenId, hashMod);
uint256 symmetry = checkSymmetry(tokenId, hashMod);
string[6] memory parts;
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 30px; }</style><rect width="100%" height="100%" fill="black" />';
parts[1] = '<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" class="base">';
parts[2] = toString(tokenId);
parts[3] = ', ';
parts[4] = toString(hashMod);
parts[5] = '</text></svg>';
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Token Hash ', toString(tokenId), ', ', toString(hashMod), '", "description": "Token Hash presents the two values from which all value and variation derive in the on-chain generative NFT as an on-chain generative NFT.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '", "attributes": [ { "trait_type": "Similarity", "value": "', toString(similarity) , '" }, { "trait_type": "Symmetry", "value": "', toString(symmetry) , '" } ] } ' ))));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
}
//Input array of addresses to whitelist and array of max mint per account
function setWhitelistAddress(address[] memory users, uint256[] memory allowedMint) public onlyOwner {
for (uint256 i = 0; i < users.length; i++) {
whitelisted[users[i]] = allowedMint[i];
}
}
//Sale logic
function setPresaleActive(bool isActive) public onlyOwner{
preSaleActive = isActive;
}
function setSaleActive(bool isActive) public onlyOwner {
standardSaleActive = isActive;
}
//Price setting
function setPrice(uint256 givenPrice) external onlyOwner {
pricePerPiece = givenPrice;
}
function getPrice() external view returns(uint256) {
return pricePerPiece;
}
//Withdrawal
function setWithdrawalAddress(address payable givenWithdrawalAddress) public onlyOwner {
withdrawalAddress = givenWithdrawalAddress;
}
function withdrawEth() public onlyOwner {
Address.sendValue(withdrawalAddress, address(this).balance);
}
//Owner info
function tokenInfo(uint256 tokenId) public view returns (address) {
return (ownerOf(tokenId));
}
function getOwners(uint256 start, uint256 end) public view returns (address[] memory){
address[] memory re = new address[](end - start);
for (uint256 i = start; i < end; i++) {
re[i - start] = ownerOf(i);
}
return re;
}
//Minting
function preMint() public payable {
require(preSaleActive, "presale not open");
require(whitelisted[msg.sender] > 0, "address not on whitelist ");
//no limit on this pre-sale
// require(whitelisted[msg.sender] > preSaleMinted[msg.sender], "exceeded mint");
mintItem();
preSaleMinted[msg.sender] += 1;
}
function mint() public payable {
require(standardSaleActive || msg.sender == owner(), "sale must be active");
require(msg.value == pricePerPiece, "must send in correct amount");
mintItem();
}
function mintItem() private returns (uint256) {
//Referencing total supply instead of keeping our own counter
require(totalSupply() < maxNumberOfPieces, "series is sold out");
require(msg.value >= pricePerPiece, "not enough eth sent ");
emit Purchase(msg.sender, msg.value, totalSupply());
uint256 tokenToMint = totalSupply();
_safeMint(msg.sender, tokenToMint);
return tokenToMint;
}
//Helpers
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
|
See {IERC721Metadata-tokenURI}./ return json from folder
|
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(baseURI(), tokenId.toString(), '.json'));
}
| 1,683,018 |
pragma solidity ^0.4.18;
import "./SafeMathLib.sol";
import "./UpgradeableToken.sol";
import "./MintableToken.sol";
/**
* A sample token that is used as a migration testing target.
*
* This is not an actual token, but just a stub used in testing.
*/
contract newToken is StandardToken, UpgradeAgent {
UpgradeableToken public oldToken;
uint public originalSupply;
function newToken(UpgradeableToken _oldToken) public {
oldToken = _oldToken;
// Let's not set bad old token
require(address(oldToken) != 0);
// Let's make sure we have something to migrate
originalSupply = _oldToken.totalSupply();
require(originalSupply != 0);
}
function upgradeFrom(address _from, uint256 _value) public {
require(msg.sender == address(oldToken));
// Mint new tokens to the migrator
totalSupply = safeAdd(totalSupply,_value);
balances[_from] = safeAdd(balances[_from],_value);
Transfer(0, _from, _value);
}
function() public payable {
revert();
}
}
|
Let's not set bad old token Let's make sure we have something to migrate
|
function newToken(UpgradeableToken _oldToken) public {
oldToken = _oldToken;
require(address(oldToken) != 0);
originalSupply = _oldToken.totalSupply();
require(originalSupply != 0);
}
| 5,376,886 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.17;
interface IERC20 {
function TOTALSUPPLY419() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF996(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER376(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE263(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM581(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER351(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL946(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB882(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB882(a, b, "SafeMath: subtraction overflow");
}
function SUB882(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL339(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV809(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV809(a, b, "SafeMath: division by zero");
}
function DIV809(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD891(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD891(a, b, "SafeMath: modulo by zero");
}
function MOD891(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT313(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function TOPAYABLE45(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE473(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER885(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFER376.selector, to, value));
}
function SAFETRANSFERFROM553(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFERFROM581.selector, from, to, value));
}
function SAFEAPPROVE341(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE696(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, value));
}
function SAFEINCREASEALLOWANCE60(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD509(value);
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE623(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB882(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN246(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT313(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//
interface IController {
function WITHDRAW936(address, uint256) external; //inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING
function EARN112(address, uint256) external; //inject NONSTANDARD NAMING
function WANT318(address) external view returns (address); //inject NONSTANDARD NAMING
function REWARDS351() external view returns (address); //inject NONSTANDARD NAMING
function VAULTS378(address) external view returns (address); //inject NONSTANDARD NAMING
function STRATEGIES650(address) external view returns (address); //inject NONSTANDARD NAMING
}
//
interface Gauge {
function DEPOSIT828(uint256) external; //inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAW936(uint256) external; //inject NONSTANDARD NAMING
}
//
interface Mintr {
function MINT422(address) external; //inject NONSTANDARD NAMING
}
//
interface Uni {
function SWAPEXACTTOKENSFORTOKENS240( //inject NONSTANDARD NAMING
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
}
//
interface ICurveFi {
function GET_VIRTUAL_PRICE800() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function REMOVE_LIQUIDITY_IMBALANCE228(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING
function REMOVE_LIQUIDITY138(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING
function EXCHANGE730( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
}
interface Zap {
function REMOVE_LIQUIDITY_ONE_COIN571( //inject NONSTANDARD NAMING
uint256,
int128,
uint256
) external;
}
//
// NOTE: Basically an alias for Vaults
interface yERC20 {
function DEPOSIT828(uint256 _amount) external; //inject NONSTANDARD NAMING
function WITHDRAW936(uint256 _amount) external; //inject NONSTANDARD NAMING
function GETPRICEPERFULLSHARE410() external view returns (uint256); //inject NONSTANDARD NAMING
}
//
interface VoterProxy {
function WITHDRAW936( //inject NONSTANDARD NAMING
address _gauge,
address _token,
uint256 _amount
) external returns (uint256);
function BALANCEOF996(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAWALL4(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING
function DEPOSIT828(address _gauge, address _token) external; //inject NONSTANDARD NAMING
function HARVEST862(address _gauge) external; //inject NONSTANDARD NAMING
function LOCK494() external; //inject NONSTANDARD NAMING
}
//
contract StrategyCurveBUSDVoterProxy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant want963 = address(0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B); //inject NONSTANDARD NAMING
address public constant crv787 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING
address public constant uni793 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING
address public constant weth737 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
address public constant dai668 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING
address public constant ydai985 = address(0xa3Aa4a71dBb17EBF2108A75b0BB7eFd9955463EF);//itoken //inject NONSTANDARD NAMING
address public constant curve489 = address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); //inject NONSTANDARD NAMING
address public constant gauge170 = address(0x69Fb7c45726cfE2baDeE8317005d3F94bE838840); //inject NONSTANDARD NAMING
address public constant voter494 = address(0x07443C1cdb3653746727D595D2c1e5B438e0535A);//CurveYCRVVoter //inject NONSTANDARD NAMING
uint256 public keepCRV = 1000;
uint256 public constant keepcrvmax536 = 10000; //inject NONSTANDARD NAMING
uint256 public performanceFee = 3000;
uint256 public constant performancemax55 = 10000; //inject NONSTANDARD NAMING
uint256 public withdrawalFee = 50;
uint256 public constant withdrawalmax744 = 10000; //inject NONSTANDARD NAMING
address public proxy;
address public governance;
address public controller;
address public strategist;
constructor(address _controller) public {
governance = msg.sender;
strategist = msg.sender;
controller = _controller;
}
function GETNAME315() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "StrategyCurveBUSDVoterProxy";
}
function SETSTRATEGIST730(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function SETKEEPCRV658(uint256 _keepCRV) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
keepCRV = _keepCRV;
}
function SETWITHDRAWALFEE696(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
withdrawalFee = _withdrawalFee;
}
function SETPERFORMANCEFEE960(uint256 _performanceFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
performanceFee = _performanceFee;
}
function SETPROXY105(address _proxy) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
proxy = _proxy;
}
function DEPOSIT828() public { //inject NONSTANDARD NAMING
uint256 _want = IERC20(want963).BALANCEOF996(address(this));
if (_want > 0) {
IERC20(want963).SAFETRANSFER885(proxy, _want);
VoterProxy(proxy).DEPOSIT828(gauge170, want963);
}
}
// Controller only function for creating additional rewards from dust
function WITHDRAW936(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(want963 != address(_asset), "want");
require(crv787 != address(_asset), "crv");
require(ydai985 != address(_asset), "ydai");
require(dai668 != address(_asset), "dai");
balance = _asset.BALANCEOF996(address(this));
_asset.SAFETRANSFER885(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW936(uint256 _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20(want963).BALANCEOF996(address(this));
if (_balance < _amount) {
_amount = _WITHDRAWSOME256(_amount.SUB882(_balance));
_amount = _amount.ADD509(_balance);
}
uint256 _fee = _amount.MUL339(withdrawalFee).DIV809(withdrawalmax744);
IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee);
address _vault = IController(controller).VAULTS378(address(want963));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want963).SAFETRANSFER885(_vault, _amount.SUB882(_fee));
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL4() external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
_WITHDRAWALL830();
balance = IERC20(want963).BALANCEOF996(address(this));
address _vault = IController(controller).VAULTS378(address(want963));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want963).SAFETRANSFER885(_vault, balance);
}
function _WITHDRAWALL830() internal { //inject NONSTANDARD NAMING
VoterProxy(proxy).WITHDRAWALL4(gauge170, want963);
}
function HARVEST862() public { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!authorized");
VoterProxy(proxy).HARVEST862(gauge170);
uint256 _crv = IERC20(crv787).BALANCEOF996(address(this));
if (_crv > 0) {
uint256 _keepCRV = _crv.MUL339(keepCRV).DIV809(keepcrvmax536);
IERC20(crv787).SAFETRANSFER885(voter494, _keepCRV);
_crv = _crv.SUB882(_keepCRV);
IERC20(crv787).SAFEAPPROVE341(uni793, 0);
IERC20(crv787).SAFEAPPROVE341(uni793, _crv);
address[] memory path = new address[](3);
path[0] = crv787;
path[1] = weth737;
path[2] = dai668;
Uni(uni793).SWAPEXACTTOKENSFORTOKENS240(_crv, uint256(0), path, address(this), now.ADD509(1800));
}
uint256 _dai = IERC20(dai668).BALANCEOF996(address(this));
if (_dai > 0) {
IERC20(dai668).SAFEAPPROVE341(ydai985, 0);
IERC20(dai668).SAFEAPPROVE341(ydai985, _dai);
yERC20(ydai985).DEPOSIT828(_dai);
}
uint256 _ydai = IERC20(ydai985).BALANCEOF996(address(this));
if (_ydai > 0) {
IERC20(ydai985).SAFEAPPROVE341(curve489, 0);
IERC20(ydai985).SAFEAPPROVE341(curve489, _ydai);
ICurveFi(curve489).ADD_LIQUIDITY808([_ydai, 0, 0, 0], 0);
}
uint256 _want = IERC20(want963).BALANCEOF996(address(this));
if (_want > 0) {
uint256 _fee = _want.MUL339(performanceFee).DIV809(performancemax55);
IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee);
DEPOSIT828();
}
VoterProxy(proxy).LOCK494();
}
function _WITHDRAWSOME256(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING
return VoterProxy(proxy).WITHDRAW936(gauge170, want963, _amount);
}
function BALANCEOFWANT761() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(want963).BALANCEOF996(address(this));
}
function BALANCEOFPOOL660() public view returns (uint256) { //inject NONSTANDARD NAMING
return VoterProxy(proxy).BALANCEOF996(gauge170);
}
function BALANCEOF996() public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEOFWANT761().ADD509(BALANCEOFPOOL660());
}
function SETGOVERNANCE812(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETCONTROLLER990(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
}
|
inject NONSTANDARD NAMING
|
function TOPAYABLE45(address account) internal pure returns (address payable) {
| 12,870,903 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.