contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | strings | library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private {
// 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))
}
}
/*
* @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 self) internal returns (slice) {
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 returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-termintaed 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 returns (slice 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 self) internal returns (slice) {
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 self) internal returns (string) {
var 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 self) internal returns (uint) {
// Starting at ptr-31 means the LSB will be the byte we care about
var ptr = self._ptr - 31;
var end = ptr + self._len;
for (uint len = 0; ptr < end; len++) {
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;
}
}
return len;
}
/*
* @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 self) internal 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 self, slice other) internal returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
var selfptr = self._ptr;
var 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
uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
var 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 self, slice other) internal 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 self, slice rune) internal returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint len;
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) {
len = 1;
} else if(b < 0xE0) {
len = 2;
} else if(b < 0xF0) {
len = 3;
} else {
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += len;
self._len -= len;
rune._len = len;
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 self) internal returns (slice 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 self) internal returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint len;
uint div = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
var b = word / div;
if (b < 0x80) {
ret = b;
len = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
len = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
len = 3;
} else {
ret = b & 0x07;
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
return 0;
}
for (uint i = 1; i < len; i++) {
div = div / 256;
b = (word / div) & 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 self) internal returns (bytes32 ret) {
assembly {
ret := sha3(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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let len := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let len := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
}
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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
var selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let len := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
var selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let len := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
}
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 returns (uint) {
uint ptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 68 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
let end := add(selfptr, sub(selflen, needlelen))
ptr := selfptr
loop:
jumpi(exit, eq(and(mload(ptr), mask), needledata))
ptr := add(ptr, 1)
jumpi(loop, lt(sub(ptr, 1), end))
ptr := add(selfptr, selflen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := sha3(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 returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 69 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
ptr := add(selfptr, sub(selflen, needlelen))
loop:
jumpi(ret, eq(and(mload(ptr), mask), needledata))
ptr := sub(ptr, 1)
jumpi(loop, gt(add(ptr, 1), selfptr))
ptr := selfptr
jump(exit)
ret:
ptr := add(ptr, needlelen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := sha3(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 self, slice needle) internal returns (slice) {
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 self, slice needle) internal returns (slice) {
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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle) internal returns (uint count) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
count++;
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 self, slice needle) internal 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 self, slice other) internal returns (string) {
var 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 self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint len = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
len += parts[i]._len;
var ret = new string(len);
uint retptr;
assembly { retptr := add(ret, 32) }
for(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 String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/ | Comment | count | function count(slice self, slice needle) internal returns (uint count) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
count++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
| /*
* @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`.
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
20941,
21301
]
} | 8,207 |
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | strings | library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private {
// 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))
}
}
/*
* @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 self) internal returns (slice) {
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 returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-termintaed 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 returns (slice 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 self) internal returns (slice) {
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 self) internal returns (string) {
var 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 self) internal returns (uint) {
// Starting at ptr-31 means the LSB will be the byte we care about
var ptr = self._ptr - 31;
var end = ptr + self._len;
for (uint len = 0; ptr < end; len++) {
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;
}
}
return len;
}
/*
* @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 self) internal 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 self, slice other) internal returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
var selfptr = self._ptr;
var 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
uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
var 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 self, slice other) internal 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 self, slice rune) internal returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint len;
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) {
len = 1;
} else if(b < 0xE0) {
len = 2;
} else if(b < 0xF0) {
len = 3;
} else {
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += len;
self._len -= len;
rune._len = len;
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 self) internal returns (slice 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 self) internal returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint len;
uint div = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
var b = word / div;
if (b < 0x80) {
ret = b;
len = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
len = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
len = 3;
} else {
ret = b & 0x07;
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
return 0;
}
for (uint i = 1; i < len; i++) {
div = div / 256;
b = (word / div) & 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 self) internal returns (bytes32 ret) {
assembly {
ret := sha3(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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let len := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let len := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
}
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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
var selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let len := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
var selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let len := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
}
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 returns (uint) {
uint ptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 68 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
let end := add(selfptr, sub(selflen, needlelen))
ptr := selfptr
loop:
jumpi(exit, eq(and(mload(ptr), mask), needledata))
ptr := add(ptr, 1)
jumpi(loop, lt(sub(ptr, 1), end))
ptr := add(selfptr, selflen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := sha3(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 returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 69 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
ptr := add(selfptr, sub(selflen, needlelen))
loop:
jumpi(ret, eq(and(mload(ptr), mask), needledata))
ptr := sub(ptr, 1)
jumpi(loop, gt(add(ptr, 1), selfptr))
ptr := selfptr
jump(exit)
ret:
ptr := add(ptr, needlelen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := sha3(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 self, slice needle) internal returns (slice) {
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 self, slice needle) internal returns (slice) {
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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle) internal returns (uint count) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
count++;
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 self, slice needle) internal 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 self, slice other) internal returns (string) {
var 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 self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint len = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
len += parts[i]._len;
var ret = new string(len);
uint retptr;
assembly { retptr := add(ret, 32) }
for(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 String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/ | Comment | contains | function contains(slice self, slice needle) internal returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
| /*
* @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.
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
21543,
21711
]
} | 8,208 |
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | strings | library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private {
// 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))
}
}
/*
* @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 self) internal returns (slice) {
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 returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-termintaed 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 returns (slice 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 self) internal returns (slice) {
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 self) internal returns (string) {
var 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 self) internal returns (uint) {
// Starting at ptr-31 means the LSB will be the byte we care about
var ptr = self._ptr - 31;
var end = ptr + self._len;
for (uint len = 0; ptr < end; len++) {
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;
}
}
return len;
}
/*
* @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 self) internal 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 self, slice other) internal returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
var selfptr = self._ptr;
var 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
uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
var 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 self, slice other) internal 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 self, slice rune) internal returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint len;
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) {
len = 1;
} else if(b < 0xE0) {
len = 2;
} else if(b < 0xF0) {
len = 3;
} else {
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += len;
self._len -= len;
rune._len = len;
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 self) internal returns (slice 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 self) internal returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint len;
uint div = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
var b = word / div;
if (b < 0x80) {
ret = b;
len = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
len = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
len = 3;
} else {
ret = b & 0x07;
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
return 0;
}
for (uint i = 1; i < len; i++) {
div = div / 256;
b = (word / div) & 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 self) internal returns (bytes32 ret) {
assembly {
ret := sha3(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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let len := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let len := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
}
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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
var selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let len := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
var selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let len := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
}
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 returns (uint) {
uint ptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 68 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
let end := add(selfptr, sub(selflen, needlelen))
ptr := selfptr
loop:
jumpi(exit, eq(and(mload(ptr), mask), needledata))
ptr := add(ptr, 1)
jumpi(loop, lt(sub(ptr, 1), end))
ptr := add(selfptr, selflen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := sha3(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 returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 69 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
ptr := add(selfptr, sub(selflen, needlelen))
loop:
jumpi(ret, eq(and(mload(ptr), mask), needledata))
ptr := sub(ptr, 1)
jumpi(loop, gt(add(ptr, 1), selfptr))
ptr := selfptr
jump(exit)
ret:
ptr := add(ptr, needlelen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := sha3(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 self, slice needle) internal returns (slice) {
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 self, slice needle) internal returns (slice) {
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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle) internal returns (uint count) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
count++;
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 self, slice needle) internal 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 self, slice other) internal returns (string) {
var 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 self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint len = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
len += parts[i]._len;
var ret = new string(len);
uint retptr;
assembly { retptr := add(ret, 32) }
for(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 String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/ | Comment | concat | function concat(slice self, slice other) internal returns (string) {
var 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 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.
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
22002,
22333
]
} | 8,209 |
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | strings | library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private {
// 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))
}
}
/*
* @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 self) internal returns (slice) {
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 returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-termintaed 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 returns (slice 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 self) internal returns (slice) {
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 self) internal returns (string) {
var 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 self) internal returns (uint) {
// Starting at ptr-31 means the LSB will be the byte we care about
var ptr = self._ptr - 31;
var end = ptr + self._len;
for (uint len = 0; ptr < end; len++) {
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;
}
}
return len;
}
/*
* @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 self) internal 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 self, slice other) internal returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
var selfptr = self._ptr;
var 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
uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
var 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 self, slice other) internal 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 self, slice rune) internal returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint len;
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) {
len = 1;
} else if(b < 0xE0) {
len = 2;
} else if(b < 0xF0) {
len = 3;
} else {
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += len;
self._len -= len;
rune._len = len;
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 self) internal returns (slice 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 self) internal returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint len;
uint div = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
var b = word / div;
if (b < 0x80) {
ret = b;
len = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
len = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
len = 3;
} else {
ret = b & 0x07;
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
return 0;
}
for (uint i = 1; i < len; i++) {
div = div / 256;
b = (word / div) & 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 self) internal returns (bytes32 ret) {
assembly {
ret := sha3(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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let len := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let len := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
}
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 self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
var selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let len := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
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 self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
var selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let len := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, len), sha3(needleptr, len))
}
}
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 returns (uint) {
uint ptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 68 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
let end := add(selfptr, sub(selflen, needlelen))
ptr := selfptr
loop:
jumpi(exit, eq(and(mload(ptr), mask), needledata))
ptr := add(ptr, 1)
jumpi(loop, lt(sub(ptr, 1), end))
ptr := add(selfptr, selflen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := sha3(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 returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 69 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
ptr := add(selfptr, sub(selflen, needlelen))
loop:
jumpi(ret, eq(and(mload(ptr), mask), needledata))
ptr := sub(ptr, 1)
jumpi(loop, gt(add(ptr, 1), selfptr))
ptr := selfptr
jump(exit)
ret:
ptr := add(ptr, needlelen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := sha3(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 self, slice needle) internal returns (slice) {
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 self, slice needle) internal returns (slice) {
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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle, slice token) internal returns (slice) {
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 self, slice needle) internal returns (slice 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 self, slice needle) internal returns (uint count) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
count++;
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 self, slice needle) internal 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 self, slice other) internal returns (string) {
var 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 self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint len = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
len += parts[i]._len;
var ret = new string(len);
uint retptr;
assembly { retptr := add(ret, 32) }
for(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 String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/ | Comment | join | function join(slice self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint len = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
len += parts[i]._len;
var ret = new string(len);
uint retptr;
assembly { retptr := add(ret, 32) }
for(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;
}
| /*
* @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`.
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
22674,
23379
]
} | 8,210 |
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | Eth2x | function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
| /*
* init
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
2553,
3090
]
} | 8,211 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | enter | function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
| /* enter into the game */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
3124,
4892
]
} | 8,212 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | getAllPlayers | function getAllPlayers() view public returns (address[])
{
return players;
}
| /*
* get players
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
4934,
5034
]
} | 8,213 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | getPlayerBetNo | function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
| /*
* get players bet no and amount
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
5494,
5626
]
} | 8,214 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | getTotalBetAmount | function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
| /*
* get players bet amount
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
6202,
6326
]
} | 8,215 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | pickWinner | function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
| /*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
7058,
11735
]
} | 8,216 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | __callback | function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
| /*TLSNotary for oraclize call */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
12339,
12775
]
} | 8,217 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | playerWithdrawPendingTransactions | function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
| /*
* public function
* in case of a failed refund or win send
*/ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
12867,
13498
]
} | 8,218 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | playerGetPendingTxByAddress | function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
| /* check for pending withdrawals */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
13543,
13712
]
} | 8,219 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerSetCallbackGasPrice | function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
lyOwner
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
| /* set gas price for oraclize callback */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
13762,
13921
]
} | 8,220 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerSetOraclizeSafeGas | function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
lyOwner
gasForOraclize = newSafeGasToOraclize;
}
| /* set gas limit for oraclize query */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
13968,
14111
]
} | 8,221 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | setOwnerProfitInPercent | function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
lyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
| /* only owner address can set ownerProfitInPercent */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
14179,
14334
]
} | 8,222 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerSetMinBet | function ownerSetMinBet(uint newMinimumBet) public
lyOwner
{
minBet = newMinimumBet;
}
| /* only owner address can set minBet */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
14382,
14498
]
} | 8,223 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerSetmaxNumber | function ownerSetmaxNumber(uint newmaxNumber) public
lyOwner
{
maxNumber = newmaxNumber;
}
| /* only owner address can set maxNumber */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
14553,
14673
]
} | 8,224 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerSetmaxPlayers | function ownerSetmaxPlayers(uint newmaxPlayers) public
lyOwner
{
maxPlayers = newmaxPlayers;
}
| /* only owner address can set maxPlayers */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
14729,
14853
]
} | 8,225 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerTransferEther | function ownerTransferEther(address sendTo, uint amount) public
lyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
| /* only owner address can transfer ether */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
14905,
15127
]
} | 8,226 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerPauseGame | function ownerPauseGame(bool newStatus) public
lyOwner
{
mePaused = newStatus;
}
| /* only owner address can set emergency pause #1 */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
15193,
15299
]
} | 8,227 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerPausePayouts | function ownerPausePayouts(bool newPayoutStatus) public
lyOwner
{
youtsPaused = newPayoutStatus;
}
| /* only owner address can set emergency pause #2 */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
15359,
15486
]
} | 8,228 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerChangeOwner | function ownerChangeOwner(address newOwner) public
lyOwner
owner = newOwner;
}
| /* only owner address can set owner address */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
15541,
15648
]
} | 8,229 |
||
Eth2x | Eth2x.sol | 0x88c8e21fd5509af42109f9cd40423f1c365a46c7 | Solidity | Eth2x | contract Eth2x is usingOraclize {
using strings for *;
using SafeMath for uint256;
/*
* checks game is currently active
*/
modifier gameIsActive {
if(gamePaused == true) throw;
_;
}
/*
* checks payouts are currently active
*/
modifier payoutsAreActive {
if(payoutsPaused == true) throw;
_;
}
/*
* checks only Oraclize address is calling
*/
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
/*
* checks only owner address is calling
*/
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
/*
* game vars
*/
uint public maxNumber = 15;
uint constant public minNumber = 0;
uint256 public lastamountSent = 0;
bool public gamePaused;
uint32 public gasForOraclize;
address public owner;
bool public payoutsPaused;
uint public contractBalance;
uint public minBet;
//init discontinued contract data
uint public maxPlayers = 100;
uint public maxPendingPayouts;
//init discontinued contract data
uint public totalWeiWon = 0;
//init discontinued contract data
uint public totalWeiWagered = 0;
uint public randomQueryID;
uint public ownerProfitInPercent = 2;
/*
* player vars
*/
address[] public players;
address[] public playersRollsZero;
address[] public playersRollsOneToSeven;
address[] public playersRollsEightToFourteen;
mapping(address => bytes32) public playerBetNo;
mapping(address => uint256) public playerBetAmountOnZero;
mapping(address => uint256) public playerBetAmountOnOneToSeven;
mapping(address => uint256) public playerBetAmountOnEightToFourteen;
uint public TotalBetAmount;
uint public TotalBetOnZero;
uint public TotalBetOneToSeven;
uint public TotalBetEightToFourteen;
mapping (address => uint) playerPendingWithdrawals;
/*
* events
*/
/* log manual refunds */
event LogRefund(bytes32 BetID, address PlayerAddress, uint RefundValue);
/* log owner transfers */
event LogOwnerTransfer(address SentToAddress, uint AmountTransferred);
event LogPlayerTransfer(address SentToAddress, uint AmountTransferred);
event logResult(uint _chosenNumber);
/*
* init
*/
function Eth2x() {
owner = msg.sender;
oraclize_setNetwork(networkID_auto);
/* use TLSNotary for oraclize call */
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
/* init min bet (0.1 ether) */
ownerSetMinBet(100000000000000000);
/* init gas for oraclize */
gasForOraclize = 535000;
/* init gas price for callback (default 20 gwei)*/
oraclize_setCustomGasPrice(26000000000 wei);
}
/* enter into the game */
function enter(bytes32 _playerBetNo) public gameIsActive payable {
require (msg.value >= minBet);
require (players.length <= maxPlayers);
playerBetNo[msg.sender] = _playerBetNo;
TotalBetAmount = TotalBetAmount.add(msg.value);
if(_playerBetNo == sha3("Zero") ){
//check for duplicate entry
if(playerBetAmountOnZero[msg.sender] == 0){
players.push(msg.sender);
playersRollsZero.push(msg.sender);
}
playerBetAmountOnZero[msg.sender] = playerBetAmountOnZero[msg.sender].add(msg.value);
TotalBetOnZero = TotalBetOnZero.add(msg.value);
}
else if(_playerBetNo == sha3("OneToSeven") ){
//check for duplicate entry
if(playerBetAmountOnOneToSeven[msg.sender] == 0){
players.push(msg.sender);
playersRollsOneToSeven.push(msg.sender);
}
playerBetAmountOnOneToSeven[msg.sender] = playerBetAmountOnOneToSeven[msg.sender].add(msg.value);
TotalBetOneToSeven = TotalBetOneToSeven.add(msg.value);
}
else if(_playerBetNo == sha3("EightToFourteen") ){
//check for duplicate entry
if(playerBetAmountOnEightToFourteen[msg.sender] == 0){
players.push(msg.sender);
playersRollsEightToFourteen.push(msg.sender);
}
playerBetAmountOnEightToFourteen[msg.sender] = playerBetAmountOnEightToFourteen[msg.sender].add(msg.value);
TotalBetEightToFourteen = TotalBetEightToFourteen.add(msg.value);
}
}
/*
* get players
*/
function getAllPlayers() view public returns (address[])
{
return players;
}
function getPlayersRollsZero() view public returns (address[])
{
return playersRollsZero;
}
function getPlayersRollsOneToSeven() view public returns (address[])
{
return playersRollsOneToSeven;
}
function getPlayersRollsEightToFourteen() view public returns (address[])
{
return playersRollsEightToFourteen;
}
/*
* get players bet no and amount
*/
function getPlayerBetNo(address _player) constant public returns (bytes32 betNo) {
return playerBetNo[_player];
}
function getPlayerBetAmountOnZero(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnZero[_player];
}
function getPlayerBetAmountOnOneToSeven(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnOneToSeven[_player];
}
function getPlayerBetAmountOnEightToFourteen(address _player) constant public returns (uint256 getAmount) {
return playerBetAmountOnEightToFourteen[_player];
}
/*
* get players bet amount
*/
function getTotalBetAmount() constant public returns (uint256 _totalBetAmount) {
return TotalBetAmount;
}
function getTotalBetOnZero() constant public returns (uint256 _totalBetOnZero) {
return TotalBetOnZero;
}
function getTotalBetOneToSeven() constant public returns (uint256 _totalBetOneToSeven) {
return TotalBetOneToSeven;
}
function getTotalBetEightToFourteen() constant public returns (uint256 _totalBetEightToFourteen) {
return TotalBetEightToFourteen;
}
function getLastamountSent() constant public returns (uint256 _lastamountSent) {
return lastamountSent;
}
/*
* public function
* player submit bet
* only if game is active & bet is valid can query oraclize and set player vars
*/
function pickWinner(uint randomNo) internal {
uint TotalBetAmount1 = TotalBetAmount.mul(ownerProfitInPercent);
TotalBetAmount1 = TotalBetAmount1.div(100);
TotalBetAmount1 = TotalBetAmount.sub(TotalBetAmount1);
lastamountSent = 0;
uint playerLength; address sendTo; uint betamount; uint percnt; uint i; uint ethToSend;
if(randomNo == 0){
playerLength = playersRollsZero.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnZero[playersRollsZero[i]].mul(100);
percnt = betamount.div(TotalBetOnZero);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnZero[playersRollsZero[i]].mul(14))){
ethToSend = playerBetAmountOnZero[playersRollsZero[i]].mul(14);
}
sendTo = playersRollsZero[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 0 && randomNo < 8){
playerLength = playersRollsOneToSeven.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(100);
percnt = betamount.div(TotalBetOneToSeven);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2))){
ethToSend = playerBetAmountOnOneToSeven[playersRollsOneToSeven[i]].mul(2);
}
sendTo = playersRollsOneToSeven[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
else if(randomNo > 7 && randomNo <= 14){
playerLength = playersRollsEightToFourteen.length;
for (i=0; i<playerLength; i++) {
/*get percentage of player bet amount*/
betamount = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(100);
percnt = betamount.div(TotalBetEightToFourteen);
ethToSend = TotalBetAmount1.mul(percnt);
ethToSend = ethToSend.div(100);
//player should win max 14x amount
if(ethToSend > (playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2))){
ethToSend = playerBetAmountOnEightToFourteen[playersRollsEightToFourteen[i]].mul(2);
}
sendTo = playersRollsEightToFourteen[i];
if(!sendTo.send(ethToSend)){
playerPendingWithdrawals[sendTo] = playerPendingWithdrawals[sendTo].add(betamount);
}
lastamountSent = lastamountSent.add(ethToSend);
LogPlayerTransfer(sendTo, ethToSend);
}
}
//store log
logResult(randomNo);
//clear vars
TotalBetAmount = 0;
TotalBetOnZero = 0;
TotalBetOneToSeven = 0;
TotalBetEightToFourteen = 0;
playersRollsZero.length = 0;
playersRollsOneToSeven.length = 0;
playersRollsEightToFourteen.length = 0;
uint j;
for(j=0; j<players.length; j++){
playerBetAmountOnZero[players[j]] = 0;
playerBetAmountOnOneToSeven[players[j]] = 0;
playerBetAmountOnEightToFourteen[players[j]] = 0;
playerBetNo[players[j]] = 0;
}
players.length = 0;
}
function rollIt() public onlyOwner {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof
uint N = 4; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, gasForOraclize); // this function internally generates the correct oraclize_query and returns its queryId
}
/*
* semi-public function - only oraclize can call
*/
/*TLSNotary for oraclize call */
function __callback(bytes32 _queryId, string _result, bytes _proof) public
onlyOraclize
payoutsAreActive
{
if (bytes(_result).length != 0 || bytes(_proof).length != 0) {
uint randomNumber = uint(sha3(_result)) % maxNumber; // this is an efficient way to get the uint out in the [0, maxRange] range
pickWinner(randomNumber); //call winner funation
}
}
/*
* public function
* in case of a failed refund or win send
*/
function playerWithdrawPendingTransactions() public
payoutsAreActive
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
/* external call to untrusted contract */
if (msg.sender.send(withdrawAmount)) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
/* check for pending withdrawals */
function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) {
return playerPendingWithdrawals[addressToCheck];
}
/* set gas price for oraclize callback */
function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public
onlyOwner
{
oraclize_setCustomGasPrice(newCallbackGasPrice);
}
/* set gas limit for oraclize query */
function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public
onlyOwner
{
gasForOraclize = newSafeGasToOraclize;
}
/* only owner address can set ownerProfitInPercent */
function setOwnerProfitInPercent(uint newMaxProfitAsPercent) public
onlyOwner
{
ownerProfitInPercent = newMaxProfitAsPercent;
}
/* only owner address can set minBet */
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
/* only owner address can set maxNumber */
function ownerSetmaxNumber(uint newmaxNumber) public
onlyOwner
{
maxNumber = newmaxNumber;
}
/* only owner address can set maxPlayers */
function ownerSetmaxPlayers(uint newmaxPlayers) public
onlyOwner
{
maxPlayers = newmaxPlayers;
}
/* only owner address can transfer ether */
function ownerTransferEther(address sendTo, uint amount) public
onlyOwner
{
/* update max profit */
if(!sendTo.send(amount)) throw;
LogOwnerTransfer(sendTo, amount);
}
/* only owner address can set emergency pause #1 */
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
/* only owner address can set emergency pause #2 */
function ownerPausePayouts(bool newPayoutStatus) public
onlyOwner
{
payoutsPaused = newPayoutStatus;
}
/* only owner address can set owner address */
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
/* only owner address can suicide - emergency */
function ownerkill() public
onlyOwner
{
suicide(owner);
}
} | ownerkill | function ownerkill() public
lyOwner
icide(owner);
| /* only owner address can suicide - emergency */ | Comment | v0.4.18+commit.9cf6e910 | None | bzzr://97596762d0cdb0978841279c5455689bee4470e7b1f2ec842907fbf57970a659 | {
"func_code_index": [
15705,
15782
]
} | 8,230 |
||
EthStarterFarming | /Volumes/Data/Projects/BscStarter/source/crispy-octo/contracts/lib/SafeERC20.sol | 0x9dfda6ca37734d69b0ebc5b65f98501ea7296893 | Solidity | SafeERC20 | 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"
);
}
}
} | /**
* @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.
*/ | NatSpecMultiLine | safeApprove | 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)
);
}
| /**
* @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.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
864,
1558
]
} | 8,231 |
||
EthStarterFarming | /Volumes/Data/Projects/BscStarter/source/crispy-octo/contracts/lib/SafeERC20.sol | 0x9dfda6ca37734d69b0ebc5b65f98501ea7296893 | Solidity | SafeERC20 | 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"
);
}
}
} | /**
* @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.
*/ | NatSpecMultiLine | _callOptionalReturn | 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"
);
}
}
| /**
* @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).
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
2868,
3715
]
} | 8,232 |
||
MandalaToken | src/MandalaToken.sol | 0xdaca87395f3b1bbc46f3fa187e996e03a5dcc985 | Solidity | MandalaToken | contract MandalaToken is ERC721Base, IERC721Metadata, Proxied {
using EnumerableSet for EnumerableSet.UintSet;
using ECDSA for bytes32;
// solhint-disable-next-line quotes
bytes internal constant TEMPLATE = 'data:text/plain,{"name":"Mandala 0x0000000000000000000000000000000000000000","description":"A Unique Mandala","image":"data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' shape-rendering=\'crispEdges\' width=\'512\' height=\'512\'><g transform=\'scale(64)\'><image width=\'8\' height=\'8\' style=\'image-rendering: pixelated;\' href=\'data:image/gif;base64,R0lGODdhEwATAMQAAAAAAPb+Y/7EJfN3NNARQUUKLG0bMsR1SujKqW7wQwe/dQBcmQeEqjDR0UgXo4A0vrlq2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkKAAAALAAAAAATABMAAAdNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGBADs=\'/></g></svg>"}';
uint256 internal constant IMAGE_DATA_POS = 521;
uint256 internal constant ADDRESS_NAME_POS = 74;
uint256 internal constant WIDTH = 19;
uint256 internal constant HEIGHT = 19;
uint256 internal constant ROW_PER_BLOCK = 4;
bytes32 constant internal xs = 0x8934893467893456789456789567896789789899000000000000000000000000;
bytes32 constant internal ys = 0x0011112222223333333444444555556666777889000000000000000000000000;
event Minted(uint256 indexed id, uint256 indexed pricePaid);
event Burned(uint256 indexed id, uint256 indexed priceReceived);
event CreatorshipTransferred(address indexed previousCreator, address indexed newCreator);
uint256 public immutable linearCoefficient;
uint256 public immutable initialPrice;
uint256 public immutable creatorCutPer10000th;
address payable public creator;
constructor(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) {
require(_creatorCutPer10000th < 2000, "CREATOR_CUT_ROO_HIGHT");
initialPrice = _initialPrice;
creatorCutPer10000th = _creatorCutPer10000th;
linearCoefficient = _linearCoefficient;
postUpgrade(_creator, _initialPrice, _creatorCutPer10000th, _linearCoefficient);
}
// solhint-disable-next-line no-unused-vars
function postUpgrade(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) public proxied {
// immutables are set in the constructor:
// initialPrice = _initialPrice;
// creatorCutPer10000th = _creatorCutPer10000th;
// linearCoefficient = _linearCoefficient;
creator = _creator;
emit CreatorshipTransferred(address(0), creator);
}
function transferCreatorship(address payable newCreatorAddress) external {
address oldCreator = creator;
require(oldCreator == msg.sender, "NOT_AUTHORIZED");
creator = newCreatorAddress;
emit CreatorshipTransferred(oldCreator, newCreatorAddress);
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure override returns (string memory) {
return "Mandala Tokens";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure override returns (string memory) {
return "MANDALA";
}
function tokenURI(uint256 id) public view virtual override returns (string memory) {
address owner = _ownerOf(id);
require(owner != address(0), "NOT_EXISTS");
return _tokenURI(id);
}
/// @notice Check if the contract supports an interface.
/// 0x01ffc9a7 is ERC165.
/// 0x80ac58cd is ERC721
/// 0x5b5e139f is for ERC721 metadata
/// 0x780e9d63 is for ERC721 enumerable
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override(ERC721Base, IERC165) returns (bool) {
return ERC721Base.supportsInterface(id) || id == 0x5b5e139f;
}
struct TokenData {
uint256 id;
string tokenURI;
}
function getTokenDataOfOwner(
address owner,
uint256 start,
uint256 num
) external view returns (TokenData[] memory tokens) {
EnumerableSet.UintSet storage allTokens = _holderTokens[owner];
uint256 balance = allTokens.length();
require(balance >= start + num, "TOO_MANY_TOKEN_REQUESTED");
tokens = new TokenData[](num);
uint256 i = 0;
while (i < num) {
uint256 id = allTokens.at(start + i);
tokens[i] = TokenData(id, _tokenURI(id));
i++;
}
}
function mint(address to, bytes memory signature) external payable returns (uint256) {
uint256 mintPrice = _curve(_supply);
require(msg.value >= mintPrice, "NOT_ENOUGH_ETH");
// -------------------------- MINTING ---------------------------------------------------------
bytes32 hashedData = keccak256(abi.encodePacked("Mandala", to));
address signer = hashedData.toEthSignedMessageHash().recover(signature);
_mint(uint256(signer), to);
// -------------------------- MINTING ---------------------------------------------------------
uint256 forCreator = mintPrice - _forReserve(mintPrice);
// responsibility of the creator to ensure it can receive the fund
bool success = true;
if (forCreator > 0) {
// solhint-disable-next-line check-send-result
success = creator.send(forCreator);
}
if(!success || msg.value > mintPrice) {
msg.sender.transfer(msg.value - mintPrice + (!success ? forCreator : 0));
}
emit Minted(uint256(signer), mintPrice);
return uint256(signer);
}
function burn(uint256 id) external {
uint256 burnPrice = _forReserve(_curve(_supply - 1));
_burn(id);
msg.sender.transfer(burnPrice);
emit Burned(id, burnPrice);
}
function currentPrice() external view returns (uint256) {
return _curve(_supply);
}
function _curve(uint256 supply) internal view returns (uint256) {
return initialPrice + supply * linearCoefficient;
}
function _forReserve(uint256 mintPrice) internal view returns (uint256) {
return mintPrice * (10000-creatorCutPer10000th) / 10000;
}
// solhint-disable-next-line code-complexity
function _tokenURI(uint256 id) internal pure returns (string memory) {
bytes memory metadata = TEMPLATE;
writeUintAsHex(metadata, ADDRESS_NAME_POS, id);
for (uint256 i = 0; i < 40; i++) {
uint8 value = uint8((id >> (40-(i+1))*4) % 16);
if (value == 0) {
value = 16; // use black as oposed to transparent
}
uint256 x = extract(xs, i);
uint256 y = extract(ys, i);
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + x + (y /ROW_PER_BLOCK) * 2 + 1, value);
if (x != y) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + y + (x /ROW_PER_BLOCK) * 2 + 1, value);
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + (WIDTH -y -1) + (x /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + y + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + (WIDTH-y-1) + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + (WIDTH -x -1) + (y /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + x + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + (WIDTH-x-1) + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
return string(metadata);
}
function setCharacter(bytes memory metadata, uint256 base, uint256 pos, uint8 value) internal pure {
uint256 base64Slot = base + (pos * 8) / 6;
uint8 bit = uint8((pos * 8) % 6);
uint8 existingValue = base64ToUint8(metadata[base64Slot]);
if (bit == 0) {
metadata[base64Slot] = uint8ToBase64(value >> 2);
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 4) << 4) | (0x0F & extraValue));
} else if (bit == 2) {
metadata[base64Slot] = uint8ToBase64((value >> 4) | (0x30 & existingValue));
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 16) << 2) | (0x03 & extraValue));
} else { // bit == 4)
// metadata[base64Slot] = uint8ToBase64((value >> 6) | (0x3C & existingValue)); // skip as value are never as big
metadata[base64Slot + 1] = uint8ToBase64(value % 64);
}
}
function extract(bytes32 arr, uint256 i) internal pure returns (uint256) {
return (uint256(arr) >> (256 - (i+1) * 4)) % 16;
}
bytes32 constant internal base64Alphabet_1 = 0x4142434445464748494A4B4C4D4E4F505152535455565758595A616263646566;
bytes32 constant internal base64Alphabet_2 = 0x6768696A6B6C6D6E6F707172737475767778797A303132333435363738392B2F;
function base64ToUint8(bytes1 s) internal pure returns (uint8 v) {
if (uint8(s) == 0x2B) {
return 62;
}
if (uint8(s) == 0x2F) {
return 63;
}
if (uint8(s) >= 0x30 && uint8(s) <= 0x39) {
return uint8(s) - 0x30 + 52;
}
if (uint8(s) >= 0x41 && uint8(s) <= 0x5A) {
return uint8(s) - 0x41;
}
if (uint8(s) >= 0x5A && uint8(s) <= 0x7A) {
return uint8(s) - 0x5A + 26;
}
return 0;
}
function uint8ToBase64(uint24 v) internal pure returns (bytes1 s) {
if (v >= 32) {
return base64Alphabet_2[v - 32];
}
return base64Alphabet_1[v];
}
bytes constant internal hexAlphabet = "0123456789abcdef";
function writeUintAsHex(bytes memory data, uint256 endPos, uint256 num) internal pure {
while (num != 0) {
data[endPos--] = bytes1(hexAlphabet[num % 16]);
num /= 16;
}
}
} | postUpgrade | function postUpgrade(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) public proxied {
// immutables are set in the constructor:
// initialPrice = _initialPrice;
// creatorCutPer10000th = _creatorCutPer10000th;
// linearCoefficient = _linearCoefficient;
creator = _creator;
emit CreatorshipTransferred(address(0), creator);
}
| // solhint-disable-next-line no-unused-vars | LineComment | v0.7.1+commit.f4a555be | MIT | {
"func_code_index": [
2621,
3061
]
} | 8,233 |
|||
MandalaToken | src/MandalaToken.sol | 0xdaca87395f3b1bbc46f3fa187e996e03a5dcc985 | Solidity | MandalaToken | contract MandalaToken is ERC721Base, IERC721Metadata, Proxied {
using EnumerableSet for EnumerableSet.UintSet;
using ECDSA for bytes32;
// solhint-disable-next-line quotes
bytes internal constant TEMPLATE = 'data:text/plain,{"name":"Mandala 0x0000000000000000000000000000000000000000","description":"A Unique Mandala","image":"data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' shape-rendering=\'crispEdges\' width=\'512\' height=\'512\'><g transform=\'scale(64)\'><image width=\'8\' height=\'8\' style=\'image-rendering: pixelated;\' href=\'data:image/gif;base64,R0lGODdhEwATAMQAAAAAAPb+Y/7EJfN3NNARQUUKLG0bMsR1SujKqW7wQwe/dQBcmQeEqjDR0UgXo4A0vrlq2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkKAAAALAAAAAATABMAAAdNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGBADs=\'/></g></svg>"}';
uint256 internal constant IMAGE_DATA_POS = 521;
uint256 internal constant ADDRESS_NAME_POS = 74;
uint256 internal constant WIDTH = 19;
uint256 internal constant HEIGHT = 19;
uint256 internal constant ROW_PER_BLOCK = 4;
bytes32 constant internal xs = 0x8934893467893456789456789567896789789899000000000000000000000000;
bytes32 constant internal ys = 0x0011112222223333333444444555556666777889000000000000000000000000;
event Minted(uint256 indexed id, uint256 indexed pricePaid);
event Burned(uint256 indexed id, uint256 indexed priceReceived);
event CreatorshipTransferred(address indexed previousCreator, address indexed newCreator);
uint256 public immutable linearCoefficient;
uint256 public immutable initialPrice;
uint256 public immutable creatorCutPer10000th;
address payable public creator;
constructor(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) {
require(_creatorCutPer10000th < 2000, "CREATOR_CUT_ROO_HIGHT");
initialPrice = _initialPrice;
creatorCutPer10000th = _creatorCutPer10000th;
linearCoefficient = _linearCoefficient;
postUpgrade(_creator, _initialPrice, _creatorCutPer10000th, _linearCoefficient);
}
// solhint-disable-next-line no-unused-vars
function postUpgrade(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) public proxied {
// immutables are set in the constructor:
// initialPrice = _initialPrice;
// creatorCutPer10000th = _creatorCutPer10000th;
// linearCoefficient = _linearCoefficient;
creator = _creator;
emit CreatorshipTransferred(address(0), creator);
}
function transferCreatorship(address payable newCreatorAddress) external {
address oldCreator = creator;
require(oldCreator == msg.sender, "NOT_AUTHORIZED");
creator = newCreatorAddress;
emit CreatorshipTransferred(oldCreator, newCreatorAddress);
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure override returns (string memory) {
return "Mandala Tokens";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure override returns (string memory) {
return "MANDALA";
}
function tokenURI(uint256 id) public view virtual override returns (string memory) {
address owner = _ownerOf(id);
require(owner != address(0), "NOT_EXISTS");
return _tokenURI(id);
}
/// @notice Check if the contract supports an interface.
/// 0x01ffc9a7 is ERC165.
/// 0x80ac58cd is ERC721
/// 0x5b5e139f is for ERC721 metadata
/// 0x780e9d63 is for ERC721 enumerable
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override(ERC721Base, IERC165) returns (bool) {
return ERC721Base.supportsInterface(id) || id == 0x5b5e139f;
}
struct TokenData {
uint256 id;
string tokenURI;
}
function getTokenDataOfOwner(
address owner,
uint256 start,
uint256 num
) external view returns (TokenData[] memory tokens) {
EnumerableSet.UintSet storage allTokens = _holderTokens[owner];
uint256 balance = allTokens.length();
require(balance >= start + num, "TOO_MANY_TOKEN_REQUESTED");
tokens = new TokenData[](num);
uint256 i = 0;
while (i < num) {
uint256 id = allTokens.at(start + i);
tokens[i] = TokenData(id, _tokenURI(id));
i++;
}
}
function mint(address to, bytes memory signature) external payable returns (uint256) {
uint256 mintPrice = _curve(_supply);
require(msg.value >= mintPrice, "NOT_ENOUGH_ETH");
// -------------------------- MINTING ---------------------------------------------------------
bytes32 hashedData = keccak256(abi.encodePacked("Mandala", to));
address signer = hashedData.toEthSignedMessageHash().recover(signature);
_mint(uint256(signer), to);
// -------------------------- MINTING ---------------------------------------------------------
uint256 forCreator = mintPrice - _forReserve(mintPrice);
// responsibility of the creator to ensure it can receive the fund
bool success = true;
if (forCreator > 0) {
// solhint-disable-next-line check-send-result
success = creator.send(forCreator);
}
if(!success || msg.value > mintPrice) {
msg.sender.transfer(msg.value - mintPrice + (!success ? forCreator : 0));
}
emit Minted(uint256(signer), mintPrice);
return uint256(signer);
}
function burn(uint256 id) external {
uint256 burnPrice = _forReserve(_curve(_supply - 1));
_burn(id);
msg.sender.transfer(burnPrice);
emit Burned(id, burnPrice);
}
function currentPrice() external view returns (uint256) {
return _curve(_supply);
}
function _curve(uint256 supply) internal view returns (uint256) {
return initialPrice + supply * linearCoefficient;
}
function _forReserve(uint256 mintPrice) internal view returns (uint256) {
return mintPrice * (10000-creatorCutPer10000th) / 10000;
}
// solhint-disable-next-line code-complexity
function _tokenURI(uint256 id) internal pure returns (string memory) {
bytes memory metadata = TEMPLATE;
writeUintAsHex(metadata, ADDRESS_NAME_POS, id);
for (uint256 i = 0; i < 40; i++) {
uint8 value = uint8((id >> (40-(i+1))*4) % 16);
if (value == 0) {
value = 16; // use black as oposed to transparent
}
uint256 x = extract(xs, i);
uint256 y = extract(ys, i);
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + x + (y /ROW_PER_BLOCK) * 2 + 1, value);
if (x != y) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + y + (x /ROW_PER_BLOCK) * 2 + 1, value);
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + (WIDTH -y -1) + (x /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + y + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + (WIDTH-y-1) + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + (WIDTH -x -1) + (y /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + x + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + (WIDTH-x-1) + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
return string(metadata);
}
function setCharacter(bytes memory metadata, uint256 base, uint256 pos, uint8 value) internal pure {
uint256 base64Slot = base + (pos * 8) / 6;
uint8 bit = uint8((pos * 8) % 6);
uint8 existingValue = base64ToUint8(metadata[base64Slot]);
if (bit == 0) {
metadata[base64Slot] = uint8ToBase64(value >> 2);
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 4) << 4) | (0x0F & extraValue));
} else if (bit == 2) {
metadata[base64Slot] = uint8ToBase64((value >> 4) | (0x30 & existingValue));
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 16) << 2) | (0x03 & extraValue));
} else { // bit == 4)
// metadata[base64Slot] = uint8ToBase64((value >> 6) | (0x3C & existingValue)); // skip as value are never as big
metadata[base64Slot + 1] = uint8ToBase64(value % 64);
}
}
function extract(bytes32 arr, uint256 i) internal pure returns (uint256) {
return (uint256(arr) >> (256 - (i+1) * 4)) % 16;
}
bytes32 constant internal base64Alphabet_1 = 0x4142434445464748494A4B4C4D4E4F505152535455565758595A616263646566;
bytes32 constant internal base64Alphabet_2 = 0x6768696A6B6C6D6E6F707172737475767778797A303132333435363738392B2F;
function base64ToUint8(bytes1 s) internal pure returns (uint8 v) {
if (uint8(s) == 0x2B) {
return 62;
}
if (uint8(s) == 0x2F) {
return 63;
}
if (uint8(s) >= 0x30 && uint8(s) <= 0x39) {
return uint8(s) - 0x30 + 52;
}
if (uint8(s) >= 0x41 && uint8(s) <= 0x5A) {
return uint8(s) - 0x41;
}
if (uint8(s) >= 0x5A && uint8(s) <= 0x7A) {
return uint8(s) - 0x5A + 26;
}
return 0;
}
function uint8ToBase64(uint24 v) internal pure returns (bytes1 s) {
if (v >= 32) {
return base64Alphabet_2[v - 32];
}
return base64Alphabet_1[v];
}
bytes constant internal hexAlphabet = "0123456789abcdef";
function writeUintAsHex(bytes memory data, uint256 endPos, uint256 num) internal pure {
while (num != 0) {
data[endPos--] = bytes1(hexAlphabet[num % 16]);
num /= 16;
}
}
} | name | function name() external pure override returns (string memory) {
return "Mandala Tokens";
}
| /// @notice A descriptive name for a collection of NFTs in this contract | NatSpecSingleLine | v0.7.1+commit.f4a555be | MIT | {
"func_code_index": [
3431,
3538
]
} | 8,234 |
|||
MandalaToken | src/MandalaToken.sol | 0xdaca87395f3b1bbc46f3fa187e996e03a5dcc985 | Solidity | MandalaToken | contract MandalaToken is ERC721Base, IERC721Metadata, Proxied {
using EnumerableSet for EnumerableSet.UintSet;
using ECDSA for bytes32;
// solhint-disable-next-line quotes
bytes internal constant TEMPLATE = 'data:text/plain,{"name":"Mandala 0x0000000000000000000000000000000000000000","description":"A Unique Mandala","image":"data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' shape-rendering=\'crispEdges\' width=\'512\' height=\'512\'><g transform=\'scale(64)\'><image width=\'8\' height=\'8\' style=\'image-rendering: pixelated;\' href=\'data:image/gif;base64,R0lGODdhEwATAMQAAAAAAPb+Y/7EJfN3NNARQUUKLG0bMsR1SujKqW7wQwe/dQBcmQeEqjDR0UgXo4A0vrlq2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkKAAAALAAAAAATABMAAAdNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGBADs=\'/></g></svg>"}';
uint256 internal constant IMAGE_DATA_POS = 521;
uint256 internal constant ADDRESS_NAME_POS = 74;
uint256 internal constant WIDTH = 19;
uint256 internal constant HEIGHT = 19;
uint256 internal constant ROW_PER_BLOCK = 4;
bytes32 constant internal xs = 0x8934893467893456789456789567896789789899000000000000000000000000;
bytes32 constant internal ys = 0x0011112222223333333444444555556666777889000000000000000000000000;
event Minted(uint256 indexed id, uint256 indexed pricePaid);
event Burned(uint256 indexed id, uint256 indexed priceReceived);
event CreatorshipTransferred(address indexed previousCreator, address indexed newCreator);
uint256 public immutable linearCoefficient;
uint256 public immutable initialPrice;
uint256 public immutable creatorCutPer10000th;
address payable public creator;
constructor(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) {
require(_creatorCutPer10000th < 2000, "CREATOR_CUT_ROO_HIGHT");
initialPrice = _initialPrice;
creatorCutPer10000th = _creatorCutPer10000th;
linearCoefficient = _linearCoefficient;
postUpgrade(_creator, _initialPrice, _creatorCutPer10000th, _linearCoefficient);
}
// solhint-disable-next-line no-unused-vars
function postUpgrade(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) public proxied {
// immutables are set in the constructor:
// initialPrice = _initialPrice;
// creatorCutPer10000th = _creatorCutPer10000th;
// linearCoefficient = _linearCoefficient;
creator = _creator;
emit CreatorshipTransferred(address(0), creator);
}
function transferCreatorship(address payable newCreatorAddress) external {
address oldCreator = creator;
require(oldCreator == msg.sender, "NOT_AUTHORIZED");
creator = newCreatorAddress;
emit CreatorshipTransferred(oldCreator, newCreatorAddress);
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure override returns (string memory) {
return "Mandala Tokens";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure override returns (string memory) {
return "MANDALA";
}
function tokenURI(uint256 id) public view virtual override returns (string memory) {
address owner = _ownerOf(id);
require(owner != address(0), "NOT_EXISTS");
return _tokenURI(id);
}
/// @notice Check if the contract supports an interface.
/// 0x01ffc9a7 is ERC165.
/// 0x80ac58cd is ERC721
/// 0x5b5e139f is for ERC721 metadata
/// 0x780e9d63 is for ERC721 enumerable
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override(ERC721Base, IERC165) returns (bool) {
return ERC721Base.supportsInterface(id) || id == 0x5b5e139f;
}
struct TokenData {
uint256 id;
string tokenURI;
}
function getTokenDataOfOwner(
address owner,
uint256 start,
uint256 num
) external view returns (TokenData[] memory tokens) {
EnumerableSet.UintSet storage allTokens = _holderTokens[owner];
uint256 balance = allTokens.length();
require(balance >= start + num, "TOO_MANY_TOKEN_REQUESTED");
tokens = new TokenData[](num);
uint256 i = 0;
while (i < num) {
uint256 id = allTokens.at(start + i);
tokens[i] = TokenData(id, _tokenURI(id));
i++;
}
}
function mint(address to, bytes memory signature) external payable returns (uint256) {
uint256 mintPrice = _curve(_supply);
require(msg.value >= mintPrice, "NOT_ENOUGH_ETH");
// -------------------------- MINTING ---------------------------------------------------------
bytes32 hashedData = keccak256(abi.encodePacked("Mandala", to));
address signer = hashedData.toEthSignedMessageHash().recover(signature);
_mint(uint256(signer), to);
// -------------------------- MINTING ---------------------------------------------------------
uint256 forCreator = mintPrice - _forReserve(mintPrice);
// responsibility of the creator to ensure it can receive the fund
bool success = true;
if (forCreator > 0) {
// solhint-disable-next-line check-send-result
success = creator.send(forCreator);
}
if(!success || msg.value > mintPrice) {
msg.sender.transfer(msg.value - mintPrice + (!success ? forCreator : 0));
}
emit Minted(uint256(signer), mintPrice);
return uint256(signer);
}
function burn(uint256 id) external {
uint256 burnPrice = _forReserve(_curve(_supply - 1));
_burn(id);
msg.sender.transfer(burnPrice);
emit Burned(id, burnPrice);
}
function currentPrice() external view returns (uint256) {
return _curve(_supply);
}
function _curve(uint256 supply) internal view returns (uint256) {
return initialPrice + supply * linearCoefficient;
}
function _forReserve(uint256 mintPrice) internal view returns (uint256) {
return mintPrice * (10000-creatorCutPer10000th) / 10000;
}
// solhint-disable-next-line code-complexity
function _tokenURI(uint256 id) internal pure returns (string memory) {
bytes memory metadata = TEMPLATE;
writeUintAsHex(metadata, ADDRESS_NAME_POS, id);
for (uint256 i = 0; i < 40; i++) {
uint8 value = uint8((id >> (40-(i+1))*4) % 16);
if (value == 0) {
value = 16; // use black as oposed to transparent
}
uint256 x = extract(xs, i);
uint256 y = extract(ys, i);
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + x + (y /ROW_PER_BLOCK) * 2 + 1, value);
if (x != y) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + y + (x /ROW_PER_BLOCK) * 2 + 1, value);
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + (WIDTH -y -1) + (x /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + y + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + (WIDTH-y-1) + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + (WIDTH -x -1) + (y /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + x + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + (WIDTH-x-1) + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
return string(metadata);
}
function setCharacter(bytes memory metadata, uint256 base, uint256 pos, uint8 value) internal pure {
uint256 base64Slot = base + (pos * 8) / 6;
uint8 bit = uint8((pos * 8) % 6);
uint8 existingValue = base64ToUint8(metadata[base64Slot]);
if (bit == 0) {
metadata[base64Slot] = uint8ToBase64(value >> 2);
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 4) << 4) | (0x0F & extraValue));
} else if (bit == 2) {
metadata[base64Slot] = uint8ToBase64((value >> 4) | (0x30 & existingValue));
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 16) << 2) | (0x03 & extraValue));
} else { // bit == 4)
// metadata[base64Slot] = uint8ToBase64((value >> 6) | (0x3C & existingValue)); // skip as value are never as big
metadata[base64Slot + 1] = uint8ToBase64(value % 64);
}
}
function extract(bytes32 arr, uint256 i) internal pure returns (uint256) {
return (uint256(arr) >> (256 - (i+1) * 4)) % 16;
}
bytes32 constant internal base64Alphabet_1 = 0x4142434445464748494A4B4C4D4E4F505152535455565758595A616263646566;
bytes32 constant internal base64Alphabet_2 = 0x6768696A6B6C6D6E6F707172737475767778797A303132333435363738392B2F;
function base64ToUint8(bytes1 s) internal pure returns (uint8 v) {
if (uint8(s) == 0x2B) {
return 62;
}
if (uint8(s) == 0x2F) {
return 63;
}
if (uint8(s) >= 0x30 && uint8(s) <= 0x39) {
return uint8(s) - 0x30 + 52;
}
if (uint8(s) >= 0x41 && uint8(s) <= 0x5A) {
return uint8(s) - 0x41;
}
if (uint8(s) >= 0x5A && uint8(s) <= 0x7A) {
return uint8(s) - 0x5A + 26;
}
return 0;
}
function uint8ToBase64(uint24 v) internal pure returns (bytes1 s) {
if (v >= 32) {
return base64Alphabet_2[v - 32];
}
return base64Alphabet_1[v];
}
bytes constant internal hexAlphabet = "0123456789abcdef";
function writeUintAsHex(bytes memory data, uint256 endPos, uint256 num) internal pure {
while (num != 0) {
data[endPos--] = bytes1(hexAlphabet[num % 16]);
num /= 16;
}
}
} | symbol | function symbol() external pure override returns (string memory) {
return "MANDALA";
}
| /// @notice An abbreviated name for NFTs in this contract | NatSpecSingleLine | v0.7.1+commit.f4a555be | MIT | {
"func_code_index": [
3602,
3704
]
} | 8,235 |
|||
MandalaToken | src/MandalaToken.sol | 0xdaca87395f3b1bbc46f3fa187e996e03a5dcc985 | Solidity | MandalaToken | contract MandalaToken is ERC721Base, IERC721Metadata, Proxied {
using EnumerableSet for EnumerableSet.UintSet;
using ECDSA for bytes32;
// solhint-disable-next-line quotes
bytes internal constant TEMPLATE = 'data:text/plain,{"name":"Mandala 0x0000000000000000000000000000000000000000","description":"A Unique Mandala","image":"data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' shape-rendering=\'crispEdges\' width=\'512\' height=\'512\'><g transform=\'scale(64)\'><image width=\'8\' height=\'8\' style=\'image-rendering: pixelated;\' href=\'data:image/gif;base64,R0lGODdhEwATAMQAAAAAAPb+Y/7EJfN3NNARQUUKLG0bMsR1SujKqW7wQwe/dQBcmQeEqjDR0UgXo4A0vrlq2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkKAAAALAAAAAATABMAAAdNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGBADs=\'/></g></svg>"}';
uint256 internal constant IMAGE_DATA_POS = 521;
uint256 internal constant ADDRESS_NAME_POS = 74;
uint256 internal constant WIDTH = 19;
uint256 internal constant HEIGHT = 19;
uint256 internal constant ROW_PER_BLOCK = 4;
bytes32 constant internal xs = 0x8934893467893456789456789567896789789899000000000000000000000000;
bytes32 constant internal ys = 0x0011112222223333333444444555556666777889000000000000000000000000;
event Minted(uint256 indexed id, uint256 indexed pricePaid);
event Burned(uint256 indexed id, uint256 indexed priceReceived);
event CreatorshipTransferred(address indexed previousCreator, address indexed newCreator);
uint256 public immutable linearCoefficient;
uint256 public immutable initialPrice;
uint256 public immutable creatorCutPer10000th;
address payable public creator;
constructor(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) {
require(_creatorCutPer10000th < 2000, "CREATOR_CUT_ROO_HIGHT");
initialPrice = _initialPrice;
creatorCutPer10000th = _creatorCutPer10000th;
linearCoefficient = _linearCoefficient;
postUpgrade(_creator, _initialPrice, _creatorCutPer10000th, _linearCoefficient);
}
// solhint-disable-next-line no-unused-vars
function postUpgrade(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) public proxied {
// immutables are set in the constructor:
// initialPrice = _initialPrice;
// creatorCutPer10000th = _creatorCutPer10000th;
// linearCoefficient = _linearCoefficient;
creator = _creator;
emit CreatorshipTransferred(address(0), creator);
}
function transferCreatorship(address payable newCreatorAddress) external {
address oldCreator = creator;
require(oldCreator == msg.sender, "NOT_AUTHORIZED");
creator = newCreatorAddress;
emit CreatorshipTransferred(oldCreator, newCreatorAddress);
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure override returns (string memory) {
return "Mandala Tokens";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure override returns (string memory) {
return "MANDALA";
}
function tokenURI(uint256 id) public view virtual override returns (string memory) {
address owner = _ownerOf(id);
require(owner != address(0), "NOT_EXISTS");
return _tokenURI(id);
}
/// @notice Check if the contract supports an interface.
/// 0x01ffc9a7 is ERC165.
/// 0x80ac58cd is ERC721
/// 0x5b5e139f is for ERC721 metadata
/// 0x780e9d63 is for ERC721 enumerable
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override(ERC721Base, IERC165) returns (bool) {
return ERC721Base.supportsInterface(id) || id == 0x5b5e139f;
}
struct TokenData {
uint256 id;
string tokenURI;
}
function getTokenDataOfOwner(
address owner,
uint256 start,
uint256 num
) external view returns (TokenData[] memory tokens) {
EnumerableSet.UintSet storage allTokens = _holderTokens[owner];
uint256 balance = allTokens.length();
require(balance >= start + num, "TOO_MANY_TOKEN_REQUESTED");
tokens = new TokenData[](num);
uint256 i = 0;
while (i < num) {
uint256 id = allTokens.at(start + i);
tokens[i] = TokenData(id, _tokenURI(id));
i++;
}
}
function mint(address to, bytes memory signature) external payable returns (uint256) {
uint256 mintPrice = _curve(_supply);
require(msg.value >= mintPrice, "NOT_ENOUGH_ETH");
// -------------------------- MINTING ---------------------------------------------------------
bytes32 hashedData = keccak256(abi.encodePacked("Mandala", to));
address signer = hashedData.toEthSignedMessageHash().recover(signature);
_mint(uint256(signer), to);
// -------------------------- MINTING ---------------------------------------------------------
uint256 forCreator = mintPrice - _forReserve(mintPrice);
// responsibility of the creator to ensure it can receive the fund
bool success = true;
if (forCreator > 0) {
// solhint-disable-next-line check-send-result
success = creator.send(forCreator);
}
if(!success || msg.value > mintPrice) {
msg.sender.transfer(msg.value - mintPrice + (!success ? forCreator : 0));
}
emit Minted(uint256(signer), mintPrice);
return uint256(signer);
}
function burn(uint256 id) external {
uint256 burnPrice = _forReserve(_curve(_supply - 1));
_burn(id);
msg.sender.transfer(burnPrice);
emit Burned(id, burnPrice);
}
function currentPrice() external view returns (uint256) {
return _curve(_supply);
}
function _curve(uint256 supply) internal view returns (uint256) {
return initialPrice + supply * linearCoefficient;
}
function _forReserve(uint256 mintPrice) internal view returns (uint256) {
return mintPrice * (10000-creatorCutPer10000th) / 10000;
}
// solhint-disable-next-line code-complexity
function _tokenURI(uint256 id) internal pure returns (string memory) {
bytes memory metadata = TEMPLATE;
writeUintAsHex(metadata, ADDRESS_NAME_POS, id);
for (uint256 i = 0; i < 40; i++) {
uint8 value = uint8((id >> (40-(i+1))*4) % 16);
if (value == 0) {
value = 16; // use black as oposed to transparent
}
uint256 x = extract(xs, i);
uint256 y = extract(ys, i);
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + x + (y /ROW_PER_BLOCK) * 2 + 1, value);
if (x != y) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + y + (x /ROW_PER_BLOCK) * 2 + 1, value);
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + (WIDTH -y -1) + (x /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + y + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + (WIDTH-y-1) + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + (WIDTH -x -1) + (y /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + x + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + (WIDTH-x-1) + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
return string(metadata);
}
function setCharacter(bytes memory metadata, uint256 base, uint256 pos, uint8 value) internal pure {
uint256 base64Slot = base + (pos * 8) / 6;
uint8 bit = uint8((pos * 8) % 6);
uint8 existingValue = base64ToUint8(metadata[base64Slot]);
if (bit == 0) {
metadata[base64Slot] = uint8ToBase64(value >> 2);
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 4) << 4) | (0x0F & extraValue));
} else if (bit == 2) {
metadata[base64Slot] = uint8ToBase64((value >> 4) | (0x30 & existingValue));
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 16) << 2) | (0x03 & extraValue));
} else { // bit == 4)
// metadata[base64Slot] = uint8ToBase64((value >> 6) | (0x3C & existingValue)); // skip as value are never as big
metadata[base64Slot + 1] = uint8ToBase64(value % 64);
}
}
function extract(bytes32 arr, uint256 i) internal pure returns (uint256) {
return (uint256(arr) >> (256 - (i+1) * 4)) % 16;
}
bytes32 constant internal base64Alphabet_1 = 0x4142434445464748494A4B4C4D4E4F505152535455565758595A616263646566;
bytes32 constant internal base64Alphabet_2 = 0x6768696A6B6C6D6E6F707172737475767778797A303132333435363738392B2F;
function base64ToUint8(bytes1 s) internal pure returns (uint8 v) {
if (uint8(s) == 0x2B) {
return 62;
}
if (uint8(s) == 0x2F) {
return 63;
}
if (uint8(s) >= 0x30 && uint8(s) <= 0x39) {
return uint8(s) - 0x30 + 52;
}
if (uint8(s) >= 0x41 && uint8(s) <= 0x5A) {
return uint8(s) - 0x41;
}
if (uint8(s) >= 0x5A && uint8(s) <= 0x7A) {
return uint8(s) - 0x5A + 26;
}
return 0;
}
function uint8ToBase64(uint24 v) internal pure returns (bytes1 s) {
if (v >= 32) {
return base64Alphabet_2[v - 32];
}
return base64Alphabet_1[v];
}
bytes constant internal hexAlphabet = "0123456789abcdef";
function writeUintAsHex(bytes memory data, uint256 endPos, uint256 num) internal pure {
while (num != 0) {
data[endPos--] = bytes1(hexAlphabet[num % 16]);
num /= 16;
}
}
} | supportsInterface | function supportsInterface(bytes4 id) public pure virtual override(ERC721Base, IERC165) returns (bool) {
return ERC721Base.supportsInterface(id) || id == 0x5b5e139f;
}
| /// @notice Check if the contract supports an interface.
/// 0x01ffc9a7 is ERC165.
/// 0x80ac58cd is ERC721
/// 0x5b5e139f is for ERC721 metadata
/// 0x780e9d63 is for ERC721 enumerable
/// @param id The id of the interface.
/// @return Whether the interface is supported. | NatSpecSingleLine | v0.7.1+commit.f4a555be | MIT | {
"func_code_index": [
4223,
4406
]
} | 8,236 |
|||
MandalaToken | src/MandalaToken.sol | 0xdaca87395f3b1bbc46f3fa187e996e03a5dcc985 | Solidity | MandalaToken | contract MandalaToken is ERC721Base, IERC721Metadata, Proxied {
using EnumerableSet for EnumerableSet.UintSet;
using ECDSA for bytes32;
// solhint-disable-next-line quotes
bytes internal constant TEMPLATE = 'data:text/plain,{"name":"Mandala 0x0000000000000000000000000000000000000000","description":"A Unique Mandala","image":"data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' shape-rendering=\'crispEdges\' width=\'512\' height=\'512\'><g transform=\'scale(64)\'><image width=\'8\' height=\'8\' style=\'image-rendering: pixelated;\' href=\'data:image/gif;base64,R0lGODdhEwATAMQAAAAAAPb+Y/7EJfN3NNARQUUKLG0bMsR1SujKqW7wQwe/dQBcmQeEqjDR0UgXo4A0vrlq2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkKAAAALAAAAAATABMAAAdNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGBADs=\'/></g></svg>"}';
uint256 internal constant IMAGE_DATA_POS = 521;
uint256 internal constant ADDRESS_NAME_POS = 74;
uint256 internal constant WIDTH = 19;
uint256 internal constant HEIGHT = 19;
uint256 internal constant ROW_PER_BLOCK = 4;
bytes32 constant internal xs = 0x8934893467893456789456789567896789789899000000000000000000000000;
bytes32 constant internal ys = 0x0011112222223333333444444555556666777889000000000000000000000000;
event Minted(uint256 indexed id, uint256 indexed pricePaid);
event Burned(uint256 indexed id, uint256 indexed priceReceived);
event CreatorshipTransferred(address indexed previousCreator, address indexed newCreator);
uint256 public immutable linearCoefficient;
uint256 public immutable initialPrice;
uint256 public immutable creatorCutPer10000th;
address payable public creator;
constructor(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) {
require(_creatorCutPer10000th < 2000, "CREATOR_CUT_ROO_HIGHT");
initialPrice = _initialPrice;
creatorCutPer10000th = _creatorCutPer10000th;
linearCoefficient = _linearCoefficient;
postUpgrade(_creator, _initialPrice, _creatorCutPer10000th, _linearCoefficient);
}
// solhint-disable-next-line no-unused-vars
function postUpgrade(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) public proxied {
// immutables are set in the constructor:
// initialPrice = _initialPrice;
// creatorCutPer10000th = _creatorCutPer10000th;
// linearCoefficient = _linearCoefficient;
creator = _creator;
emit CreatorshipTransferred(address(0), creator);
}
function transferCreatorship(address payable newCreatorAddress) external {
address oldCreator = creator;
require(oldCreator == msg.sender, "NOT_AUTHORIZED");
creator = newCreatorAddress;
emit CreatorshipTransferred(oldCreator, newCreatorAddress);
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure override returns (string memory) {
return "Mandala Tokens";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure override returns (string memory) {
return "MANDALA";
}
function tokenURI(uint256 id) public view virtual override returns (string memory) {
address owner = _ownerOf(id);
require(owner != address(0), "NOT_EXISTS");
return _tokenURI(id);
}
/// @notice Check if the contract supports an interface.
/// 0x01ffc9a7 is ERC165.
/// 0x80ac58cd is ERC721
/// 0x5b5e139f is for ERC721 metadata
/// 0x780e9d63 is for ERC721 enumerable
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override(ERC721Base, IERC165) returns (bool) {
return ERC721Base.supportsInterface(id) || id == 0x5b5e139f;
}
struct TokenData {
uint256 id;
string tokenURI;
}
function getTokenDataOfOwner(
address owner,
uint256 start,
uint256 num
) external view returns (TokenData[] memory tokens) {
EnumerableSet.UintSet storage allTokens = _holderTokens[owner];
uint256 balance = allTokens.length();
require(balance >= start + num, "TOO_MANY_TOKEN_REQUESTED");
tokens = new TokenData[](num);
uint256 i = 0;
while (i < num) {
uint256 id = allTokens.at(start + i);
tokens[i] = TokenData(id, _tokenURI(id));
i++;
}
}
function mint(address to, bytes memory signature) external payable returns (uint256) {
uint256 mintPrice = _curve(_supply);
require(msg.value >= mintPrice, "NOT_ENOUGH_ETH");
// -------------------------- MINTING ---------------------------------------------------------
bytes32 hashedData = keccak256(abi.encodePacked("Mandala", to));
address signer = hashedData.toEthSignedMessageHash().recover(signature);
_mint(uint256(signer), to);
// -------------------------- MINTING ---------------------------------------------------------
uint256 forCreator = mintPrice - _forReserve(mintPrice);
// responsibility of the creator to ensure it can receive the fund
bool success = true;
if (forCreator > 0) {
// solhint-disable-next-line check-send-result
success = creator.send(forCreator);
}
if(!success || msg.value > mintPrice) {
msg.sender.transfer(msg.value - mintPrice + (!success ? forCreator : 0));
}
emit Minted(uint256(signer), mintPrice);
return uint256(signer);
}
function burn(uint256 id) external {
uint256 burnPrice = _forReserve(_curve(_supply - 1));
_burn(id);
msg.sender.transfer(burnPrice);
emit Burned(id, burnPrice);
}
function currentPrice() external view returns (uint256) {
return _curve(_supply);
}
function _curve(uint256 supply) internal view returns (uint256) {
return initialPrice + supply * linearCoefficient;
}
function _forReserve(uint256 mintPrice) internal view returns (uint256) {
return mintPrice * (10000-creatorCutPer10000th) / 10000;
}
// solhint-disable-next-line code-complexity
function _tokenURI(uint256 id) internal pure returns (string memory) {
bytes memory metadata = TEMPLATE;
writeUintAsHex(metadata, ADDRESS_NAME_POS, id);
for (uint256 i = 0; i < 40; i++) {
uint8 value = uint8((id >> (40-(i+1))*4) % 16);
if (value == 0) {
value = 16; // use black as oposed to transparent
}
uint256 x = extract(xs, i);
uint256 y = extract(ys, i);
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + x + (y /ROW_PER_BLOCK) * 2 + 1, value);
if (x != y) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + y + (x /ROW_PER_BLOCK) * 2 + 1, value);
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + (WIDTH -y -1) + (x /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + y + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + (WIDTH-y-1) + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + (WIDTH -x -1) + (y /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + x + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + (WIDTH-x-1) + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
return string(metadata);
}
function setCharacter(bytes memory metadata, uint256 base, uint256 pos, uint8 value) internal pure {
uint256 base64Slot = base + (pos * 8) / 6;
uint8 bit = uint8((pos * 8) % 6);
uint8 existingValue = base64ToUint8(metadata[base64Slot]);
if (bit == 0) {
metadata[base64Slot] = uint8ToBase64(value >> 2);
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 4) << 4) | (0x0F & extraValue));
} else if (bit == 2) {
metadata[base64Slot] = uint8ToBase64((value >> 4) | (0x30 & existingValue));
uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]);
metadata[base64Slot + 1] = uint8ToBase64(((value % 16) << 2) | (0x03 & extraValue));
} else { // bit == 4)
// metadata[base64Slot] = uint8ToBase64((value >> 6) | (0x3C & existingValue)); // skip as value are never as big
metadata[base64Slot + 1] = uint8ToBase64(value % 64);
}
}
function extract(bytes32 arr, uint256 i) internal pure returns (uint256) {
return (uint256(arr) >> (256 - (i+1) * 4)) % 16;
}
bytes32 constant internal base64Alphabet_1 = 0x4142434445464748494A4B4C4D4E4F505152535455565758595A616263646566;
bytes32 constant internal base64Alphabet_2 = 0x6768696A6B6C6D6E6F707172737475767778797A303132333435363738392B2F;
function base64ToUint8(bytes1 s) internal pure returns (uint8 v) {
if (uint8(s) == 0x2B) {
return 62;
}
if (uint8(s) == 0x2F) {
return 63;
}
if (uint8(s) >= 0x30 && uint8(s) <= 0x39) {
return uint8(s) - 0x30 + 52;
}
if (uint8(s) >= 0x41 && uint8(s) <= 0x5A) {
return uint8(s) - 0x41;
}
if (uint8(s) >= 0x5A && uint8(s) <= 0x7A) {
return uint8(s) - 0x5A + 26;
}
return 0;
}
function uint8ToBase64(uint24 v) internal pure returns (bytes1 s) {
if (v >= 32) {
return base64Alphabet_2[v - 32];
}
return base64Alphabet_1[v];
}
bytes constant internal hexAlphabet = "0123456789abcdef";
function writeUintAsHex(bytes memory data, uint256 endPos, uint256 num) internal pure {
while (num != 0) {
data[endPos--] = bytes1(hexAlphabet[num % 16]);
num /= 16;
}
}
} | _tokenURI | function _tokenURI(uint256 id) internal pure returns (string memory) {
bytes memory metadata = TEMPLATE;
writeUintAsHex(metadata, ADDRESS_NAME_POS, id);
for (uint256 i = 0; i < 40; i++) {
uint8 value = uint8((id >> (40-(i+1))*4) % 16);
if (value == 0) {
value = 16; // use black as oposed to transparent
}
uint256 x = extract(xs, i);
uint256 y = extract(ys, i);
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + x + (y /ROW_PER_BLOCK) * 2 + 1, value);
if (x != y) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + y + (x /ROW_PER_BLOCK) * 2 + 1, value);
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + (WIDTH -y -1) + (x /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + y + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + (WIDTH-y-1) + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
if (x != WIDTH / 2) {
setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + (WIDTH -x -1) + (y /ROW_PER_BLOCK) * 2 + 1, value); // x mirror
}
if (y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + x + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror
}
if (x != WIDTH / 2 && y != HEIGHT / 2) {
setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + (WIDTH-x-1) + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror
}
}
return string(metadata);
}
| // solhint-disable-next-line code-complexity | LineComment | v0.7.1+commit.f4a555be | MIT | {
"func_code_index": [
6845,
8813
]
} | 8,237 |
|||
UniverseFactory | UniverseFactory.sol | 0xe62e470c8fba49aea4e87779d536c5923d01bb95 | Solidity | SafeMathUint256 | library SafeMathUint256 {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a <= b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a;
} else {
return b;
}
}
function getUint256Min() internal pure returns (uint256) {
return 0;
}
function getUint256Max() internal pure returns (uint256) {
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) {
return a % b == 0;
}
// Float [fixed point] Operations
function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, b), base);
}
function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, base), b);
}
} | fxpMul | function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, b), base);
}
| // Float [fixed point] Operations | LineComment | v0.4.20+commit.3155dd80 | bzzr://f29d68c633b53a5bd945494fdcf325defec4766c304d51219d778f057b4317ae | {
"func_code_index": [
1548,
1683
]
} | 8,238 |
|||
UniverseFactory | UniverseFactory.sol | 0xe62e470c8fba49aea4e87779d536c5923d01bb95 | Solidity | Order | library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IOrders orders;
IMarket market;
IAugur augur;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
//
// Constructor
//
// No validation is needed here as it is simply a librarty function for organizing data
function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) {
require(_outcome < _market.getNumberOfOutcomes());
require(_price < _market.getNumTicks());
IOrders _orders = IOrders(_controller.lookup("Orders"));
IAugur _augur = _controller.getAugur();
return Data({
orders: _orders,
market: _market,
augur: _augur,
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function getOrderId(Order.Data _orderData) internal view returns (bytes32) {
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = _orderData.orders.getOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orderData.orders.getAmount(_orderId) == 0);
_orderData.id = _orderId;
}
return _orderData.id;
}
function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) {
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) {
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function escrowFunds(Order.Data _orderData) internal returns (bool) {
if (_orderData.orderType == Order.Types.Ask) {
return escrowFundsForAsk(_orderData);
} else if (_orderData.orderType == Order.Types.Bid) {
return escrowFundsForBid(_orderData);
}
}
function saveOrder(Order.Data _orderData, bytes32 _tradeGroupId) internal returns (bytes32) {
return _orderData.orders.saveOrder(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.betterOrderId, _orderData.worseOrderId, _tradeGroupId);
}
//
// Private functions
//
function escrowFundsForBid(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
uint256 _attosharesToCover = _orderData.amount;
uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes();
// Figure out how many almost-complete-sets (just missing `outcome` share) the creator has
uint256 _attosharesHeld = 2**254;
for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator);
_attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld);
}
}
// Take shares into escrow if they have any almost-complete-sets
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
for (_i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
_orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
}
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
function escrowFundsForAsk(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
IShareToken _shareToken = _orderData.market.getShareToken(_orderData.outcome);
uint256 _attosharesToCover = _orderData.amount;
// Figure out how many shares of the outcome the creator has
uint256 _attosharesHeld = _shareToken.balanceOf(_orderData.creator);
// Take shares in escrow if user has shares
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
_shareToken.trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _orderData.market.getNumTicks().sub(_orderData.price).mul(_attosharesToCover);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
} | create | function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) {
require(_outcome < _market.getNumberOfOutcomes());
require(_price < _market.getNumTicks());
IOrders _orders = IOrders(_controller.lookup("Orders"));
IAugur _augur = _controller.getAugur();
return Data({
orders: _orders,
market: _market,
augur: _augur,
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
| //
// Constructor
//
// No validation is needed here as it is simply a librarty function for organizing data | LineComment | v0.4.20+commit.3155dd80 | bzzr://f29d68c633b53a5bd945494fdcf325defec4766c304d51219d778f057b4317ae | {
"func_code_index": [
718,
1635
]
} | 8,239 |
|||
UniverseFactory | UniverseFactory.sol | 0xe62e470c8fba49aea4e87779d536c5923d01bb95 | Solidity | Order | library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IOrders orders;
IMarket market;
IAugur augur;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
//
// Constructor
//
// No validation is needed here as it is simply a librarty function for organizing data
function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) {
require(_outcome < _market.getNumberOfOutcomes());
require(_price < _market.getNumTicks());
IOrders _orders = IOrders(_controller.lookup("Orders"));
IAugur _augur = _controller.getAugur();
return Data({
orders: _orders,
market: _market,
augur: _augur,
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function getOrderId(Order.Data _orderData) internal view returns (bytes32) {
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = _orderData.orders.getOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orderData.orders.getAmount(_orderId) == 0);
_orderData.id = _orderId;
}
return _orderData.id;
}
function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) {
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) {
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function escrowFunds(Order.Data _orderData) internal returns (bool) {
if (_orderData.orderType == Order.Types.Ask) {
return escrowFundsForAsk(_orderData);
} else if (_orderData.orderType == Order.Types.Bid) {
return escrowFundsForBid(_orderData);
}
}
function saveOrder(Order.Data _orderData, bytes32 _tradeGroupId) internal returns (bytes32) {
return _orderData.orders.saveOrder(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.betterOrderId, _orderData.worseOrderId, _tradeGroupId);
}
//
// Private functions
//
function escrowFundsForBid(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
uint256 _attosharesToCover = _orderData.amount;
uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes();
// Figure out how many almost-complete-sets (just missing `outcome` share) the creator has
uint256 _attosharesHeld = 2**254;
for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator);
_attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld);
}
}
// Take shares into escrow if they have any almost-complete-sets
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
for (_i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
_orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
}
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
function escrowFundsForAsk(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
IShareToken _shareToken = _orderData.market.getShareToken(_orderData.outcome);
uint256 _attosharesToCover = _orderData.amount;
// Figure out how many shares of the outcome the creator has
uint256 _attosharesHeld = _shareToken.balanceOf(_orderData.creator);
// Take shares in escrow if user has shares
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
_shareToken.trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _orderData.market.getNumTicks().sub(_orderData.price).mul(_attosharesToCover);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
} | getOrderId | function getOrderId(Order.Data _orderData) internal view returns (bytes32) {
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = _orderData.orders.getOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orderData.orders.getAmount(_orderId) == 0);
_orderData.id = _orderId;
}
return _orderData.id;
}
| //
// "public" functions
// | LineComment | v0.4.20+commit.3155dd80 | bzzr://f29d68c633b53a5bd945494fdcf325defec4766c304d51219d778f057b4317ae | {
"func_code_index": [
1683,
2209
]
} | 8,240 |
|||
UniverseFactory | UniverseFactory.sol | 0xe62e470c8fba49aea4e87779d536c5923d01bb95 | Solidity | Order | library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IOrders orders;
IMarket market;
IAugur augur;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
//
// Constructor
//
// No validation is needed here as it is simply a librarty function for organizing data
function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) {
require(_outcome < _market.getNumberOfOutcomes());
require(_price < _market.getNumTicks());
IOrders _orders = IOrders(_controller.lookup("Orders"));
IAugur _augur = _controller.getAugur();
return Data({
orders: _orders,
market: _market,
augur: _augur,
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function getOrderId(Order.Data _orderData) internal view returns (bytes32) {
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = _orderData.orders.getOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orderData.orders.getAmount(_orderId) == 0);
_orderData.id = _orderId;
}
return _orderData.id;
}
function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) {
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) {
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function escrowFunds(Order.Data _orderData) internal returns (bool) {
if (_orderData.orderType == Order.Types.Ask) {
return escrowFundsForAsk(_orderData);
} else if (_orderData.orderType == Order.Types.Bid) {
return escrowFundsForBid(_orderData);
}
}
function saveOrder(Order.Data _orderData, bytes32 _tradeGroupId) internal returns (bytes32) {
return _orderData.orders.saveOrder(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.betterOrderId, _orderData.worseOrderId, _tradeGroupId);
}
//
// Private functions
//
function escrowFundsForBid(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
uint256 _attosharesToCover = _orderData.amount;
uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes();
// Figure out how many almost-complete-sets (just missing `outcome` share) the creator has
uint256 _attosharesHeld = 2**254;
for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator);
_attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld);
}
}
// Take shares into escrow if they have any almost-complete-sets
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
for (_i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
_orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
}
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
function escrowFundsForAsk(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
IShareToken _shareToken = _orderData.market.getShareToken(_orderData.outcome);
uint256 _attosharesToCover = _orderData.amount;
// Figure out how many shares of the outcome the creator has
uint256 _attosharesHeld = _shareToken.balanceOf(_orderData.creator);
// Take shares in escrow if user has shares
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
_shareToken.trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _orderData.market.getNumTicks().sub(_orderData.price).mul(_attosharesToCover);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
} | escrowFundsForBid | function escrowFundsForBid(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
uint256 _attosharesToCover = _orderData.amount;
uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes();
// Figure out how many almost-complete-sets (just missing `outcome` share) the creator has
uint256 _attosharesHeld = 2**254;
for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator);
_attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld);
}
}
// Take shares into escrow if they have any almost-complete-sets
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
for (_i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
_orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
}
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
| //
// Private functions
// | LineComment | v0.4.20+commit.3155dd80 | bzzr://f29d68c633b53a5bd945494fdcf325defec4766c304d51219d778f057b4317ae | {
"func_code_index": [
3447,
5252
]
} | 8,241 |
|||
CoreVault | contracts/INBUNIERC20.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | INBUNIERC20 | interface INBUNIERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
event Log(string log);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
99,
159
]
} | 8,242 |
CoreVault | contracts/INBUNIERC20.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | INBUNIERC20 | interface INBUNIERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
event Log(string log);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) external view returns (uint256);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
242,
315
]
} | 8,243 |
CoreVault | contracts/INBUNIERC20.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | INBUNIERC20 | interface INBUNIERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
event Log(string log);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transfer | function transfer(address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
539,
621
]
} | 8,244 |
CoreVault | contracts/INBUNIERC20.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | INBUNIERC20 | interface INBUNIERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
event Log(string log);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) external view returns (uint256);
| /**
* @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.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
900,
988
]
} | 8,245 |
CoreVault | contracts/INBUNIERC20.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | INBUNIERC20 | interface INBUNIERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
event Log(string log);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 amount) external returns (bool);
| /**
* @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.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
1652,
1731
]
} | 8,246 |
CoreVault | contracts/INBUNIERC20.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | INBUNIERC20 | interface INBUNIERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
event Log(string log);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address sender, address recipient, 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.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
2044,
2146
]
} | 8,247 |
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | onERC721Received | function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
| /**
* @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`.
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
1860,
2043
]
} | 8,248 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | onERC1155BatchReceived | function onERC1155BatchReceived(address operator, address from, uint256[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
| /**
* @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
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
2962,
3182
]
} | 8,249 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | setRaffleTicket | function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
| /**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
3324,
3552
]
} | 8,250 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | onERC1155Received | function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
| /**
* @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
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
4310,
4505
]
} | 8,251 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | supportsInterface | function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
| // ERC165 interface support | LineComment | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
4536,
4796
]
} | 8,252 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | startRaffle | function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
| /**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
5053,
5600
]
} | 8,253 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | getPlayersLength | function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
| /**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
5867,
6008
]
} | 8,254 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | getPrizesLength | function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
| /**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
6252,
6391
]
} | 8,255 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | changeWithdrawGracePeriod | function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
| /**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
6562,
6774
]
} | 8,256 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | getPlayerAtIndex | function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
| /**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
7010,
7317
]
} | 8,257 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | getPrizeAtIndex | function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
| /**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
7557,
7806
]
} | 8,258 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | draftWinners | function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
| /**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
8103,
8724
]
} | 8,259 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | claimPrize | function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
| /**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
8927,
9441
]
} | 8,260 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | getPrizeWinner | function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
| /**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
9701,
9934
]
} | 8,261 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | getPrizeWinnerIndex | function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
| /**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
10192,
10748
]
} | 8,262 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | unlockUnclaimedPrize | function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
| /**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
11020,
11449
]
} | 8,263 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | _addPrize | function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
| /**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
11835,
12236
]
} | 8,264 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | addERC1155Prize | function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
| /**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
12563,
12963
]
} | 8,265 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | addERC721Prize | function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
| /**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
13289,
13678
]
} | 8,266 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | enterGame | function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
| /**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
13948,
14380
]
} | 8,267 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | _transferPrize | function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
| /**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
14648,
15279
]
} | 8,268 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | getRandomNumber | function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
| /**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
15523,
15964
]
} | 8,269 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | fulfillRandomness | function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
| /**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
16186,
16543
]
} | 8,270 |
|
Raffle | contracts/Raffle/Raffle.sol | 0x13838388afa16c7a2507dd65feb961b53bb7b78c | Solidity | Raffle | contract Raffle is IRaffle, RaffleAdminAccessControl, IERC721Receiver, IERC1155Receiver, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) public randomnessRequests;
RaffleInfo[] public raffleInfo;
ERC1155 public raffleTicket;
uint256 public withdrawGracePeriod;
constructor(
address raffleTicketAddress,
bytes32 _keyHash,
address VRFCoordinator,
address LINKToken,
uint256 _fee
)
VRFConsumerBase(
VRFCoordinator, // VRF Coordinator
LINKToken // LINK Token
)
RaffleAdminAccessControl(
msg.sender,
raffleTicketAddress
)
public
{
keyHash = _keyHash;
fee = _fee;
setRaffleTicket(raffleTicketAddress);
changeWithdrawGracePeriod(60 * 60 * 24 * 7); // 1 week in seconds
}
modifier raffleExists(uint256 raffleIndex) {
require(raffleInfo.length > raffleIndex, 'Raffle: Raffle does not exists');
_;
}
modifier raffleIsRunning(uint256 raffleIndex) {
require(
raffleInfo[raffleIndex].startDate <= now() &&
now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle not running'
);
_;
}
modifier raffleIsConcluded(uint256 raffleIndex) {
require(now() >= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is not concluded yet');
_;
}
modifier raffleIsNotConcluded(uint256 raffleIndex) {
require(now() <= raffleInfo[raffleIndex].endDate, 'Raffle: Raffle is already concluded');
_;
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @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[] memory ids, uint256[] memory values, bytes calldata data) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev It allows to set a new raffle ticket.
* @param raffleTicketAddress The raffleTicketAddress. It must be ERC-1155 token.
*/
function setRaffleTicket(address raffleTicketAddress) public override onlyManager {
require(raffleTicketAddress != address(0), 'Raffle: RaffleTicket address cannot be zero');
raffleTicket = ERC1155(raffleTicketAddress);
}
/**
* @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) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
// ERC165 interface support
function supportsInterface(bytes4 interfaceID) public pure override(IERC165, AccessControlEnumerable) returns (bool) {
return interfaceID == 0x01ffc9a7 || // ERC165
interfaceID == 0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
}
/**
* @dev Initiate a new raffle.
* Only the Owner can call this method.
* @param startDate The timestamp after when a raffle starts
* @param endDate The timestamp after when a raffle can be finalised
* @return (uint256) the index of the raffle
*/
function startRaffle(uint startDate, uint endDate) public override onlyManager returns (uint256) {
require(startDate > now(), 'Raffle: Start date should be later than current block time');
require(startDate < endDate, 'Raffle: End date should be later than start date');
raffleInfo.push();
uint256 newIndex = raffleInfo.length - 1;
raffleInfo[newIndex].startDate = startDate;
raffleInfo[newIndex].endDate = endDate;
raffleInfo[newIndex].randomResult = 0;
emit RaffleStarted(newIndex, startDate, endDate);
return newIndex;
}
/**
* @dev This function helps to get a better picture of a given raffle. It also
* @dev helps in verifying offchain the fairness of the Raffle.
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of players in the raffle
*/
function getPlayersLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].players.length;
}
/**
* @dev This function helps to get a better picture of a given raffle by
* @dev helping retrieving the number of Prizes
* @param raffleIndex The index of the Raffle to check.
* @return (uint256) the number of prizes in the raffle
*/
function getPrizesLength(uint256 raffleIndex) public override view returns (uint256) {
return raffleInfo[raffleIndex].prizes.length;
}
/**
* @dev With this function the Owner can change the grace period
* @dev to withdraw unclamed Prices
* @param period The length of the grace period in seconds
*/
function changeWithdrawGracePeriod(uint256 period) public onlyManager override {
require(period >= 60 * 60 * 24 * 7, 'Withdraw grace period too short'); // 1 week in seconds
withdrawGracePeriod = period;
}
/**
* @dev A handy getter for a Player of a given Raffle.
* @param raffleIndex the index of the Raffle where to get the Player
* @param playerIndex the index of the Player to get
* @return (address) the address of the player
*/
function getPlayerAtIndex(
uint256 raffleIndex,
uint256 playerIndex
)
public
view
override
raffleExists(raffleIndex)
returns (address)
{
require(playerIndex < raffleInfo[raffleIndex].players.length, 'Raffle: No Player at index');
return raffleInfo[raffleIndex].players[playerIndex];
}
/**
* @dev A handy getter for the Prizes
* @param raffleIndex the index of the Raffle where to get the Player
* @param prizeIndex the index of the Prize to get
* @return (address, uint256) the prize address and the prize tokenId
*/
function getPrizeAtIndex(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address, uint256) {
return (
raffleInfo[raffleIndex].prizes[prizeIndex].tokenAddress,
raffleInfo[raffleIndex].prizes[prizeIndex].tokenId
);
}
/**
* @dev This method disclosed the committed message and closes the current raffle.
* Only the Owner can call this method
* @param raffleIndex the index of the Raffle where to draft winners
* @param entropy The message in clear. It will be used as part of entropy from Chainlink
*/
function draftWinners(
uint256 raffleIndex,
uint256 entropy
)
public
override
onlyManager
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(raffleInfo[raffleIndex].randomResult == 0, 'Raffle: Randomness already requested');
raffleInfo[raffleIndex].randomResult = 1; // 1 is our flag for 'pending'
if(getPlayersLength(raffleIndex) > 0 && getPrizesLength(raffleIndex) > 0) {
getRandomNumber(raffleIndex, entropy);
}
else {
raffleInfo[raffleIndex].randomResult = 2; // 2 is our flag for 'concluded without Players or Prizes'
emit WinnersDrafted(raffleIndex, 2);
}
}
/**
* @dev Allows a winner to withdraw his/her prize
* @param raffleIndex The index of the Raffle where to find the Price to withdraw
* @param prizeIndex The index of the Prize to withdraw
*/
function claimPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
raffleExists(raffleIndex)
raffleIsConcluded(raffleIndex)
{
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Random Number not drafted yet'
);
address prizeWinner = getPrizeWinner(raffleIndex, prizeIndex);
require(msg.sender == prizeWinner, 'Raffle: You are not the winner of this Prize');
_transferPrize(raffleIndex, prizeIndex, prizeWinner);
}
/**
* @dev It maps a given Prize with the address of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinner(uint256 raffleIndex, uint256 prizeIndex) public override view returns (address) {
uint winnerIndex = getPrizeWinnerIndex(raffleIndex, prizeIndex);
return raffleInfo[raffleIndex].players[winnerIndex];
}
/**
* @dev It maps a given Prize with the index of the winner.
* @param raffleIndex The index of the Raffle where to find the Price winner
* @param prizeIndex The index of the prize to withdraw
* @return (uint256) The index of the winning account
*/
function getPrizeWinnerIndex(
uint256 raffleIndex,
uint256 prizeIndex
)
public
override
view
raffleIsConcluded(raffleIndex)
returns (uint256)
{
require(getPlayersLength(raffleIndex) > 0, 'Raffle: Raffle concluded without Players');
require(
raffleInfo[raffleIndex].randomResult != 0 &&
raffleInfo[raffleIndex].randomResult != 1,
'Raffle: Randomness pending'
);
bytes32 randomNumber = keccak256(abi.encode(raffleInfo[raffleIndex].randomResult + prizeIndex));
return uint(randomNumber) % getPlayersLength(raffleIndex);
}
/**
* @dev Prevents locked NFT by allowing the Owner to withdraw an unclaimed
* @dev prize after a grace period has passed
* @param raffleIndex The index of the Raffle containing the Prize to withdraw
* @param prizeIndex The index of the prize to withdraw
*/
function unlockUnclaimedPrize(
uint256 raffleIndex,
uint prizeIndex
)
public
override
onlyPrizeManager
raffleIsConcluded(raffleIndex)
{
require(
now() >= raffleInfo[raffleIndex].endDate + withdrawGracePeriod ||
getPlayersLength(raffleIndex) == 0, // if there is no players, we can withdraw immediately
'Raffle: Grace period not passed yet'
);
_transferPrize(raffleIndex, prizeIndex, msg.sender);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
* @param prizeType the type of prize to add. 0=ERC1155, 1=ERC721
*/
function _addPrize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId,
PrizeType prizeType
) internal {
Prize memory prize;
prize.tokenAddress = tokenAddress;
prize.tokenId = tokenId;
prize.prizeType = prizeType;
raffleInfo[raffleIndex].prizes.push(prize);
uint256 prizeIndex = raffleInfo[raffleIndex].prizes.length - 1;
emit PrizeAdded(raffleIndex, prizeIndex);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC1155 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC1155Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC1155 prizeInstance = ERC1155(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId, 1, '');
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC1155);
}
/**
* @dev Once a non-ticket NFT is received, it is considered as prize
* @dev play multiple tickets.
* @notice MUST trigger PrizeAdded event
* @dev With this function, we add the received ERC721 NFT as raffle Prize
* @param tokenAddress the address of the NFT received
* @param tokenId the id of the NFT received
*/
function addERC721Prize(
uint256 raffleIndex,
address tokenAddress,
uint256 tokenId
)
public
override
onlyPrizeManager
raffleExists(raffleIndex)
raffleIsNotConcluded(raffleIndex)
{
ERC721 prizeInstance = ERC721(tokenAddress);
prizeInstance.safeTransferFrom(msg.sender, address(this), tokenId);
_addPrize(raffleIndex, tokenAddress, tokenId, PrizeType.ERC721);
}
/**
* @dev Anyone with a valid ticket can enter the raffle. One player can also
* @dev play multiple tickets.
* @notice MUST trigger EnteredGame event
* @param raffleIndex The index of the Raffle to enter
* @param ticketsAmount the number of tickets to play
*/
function enterGame(
uint256 raffleIndex,
uint256 ticketsAmount
)
public
override
raffleExists(raffleIndex)
raffleIsRunning(raffleIndex)
{
raffleTicket.safeTransferFrom(msg.sender, address(this), 0, ticketsAmount, '');
for (uint i = 0; i < ticketsAmount; i++) {
raffleInfo[raffleIndex].players.push(msg.sender);
emit EnteredGame(raffleIndex, msg.sender, raffleInfo[raffleIndex].players.length - 1);
}
}
/**
* @dev It transfers the prize to a given address.
* @notice MUST trigger WinnersDrafted event
* @param raffleIndex The index of the Raffle to enter
* @param prizeIndex The index of the prize to withdraw
* @param winnerAddress The address of the winner
*/
function _transferPrize(uint256 raffleIndex, uint prizeIndex, address winnerAddress) internal {
Prize storage prize = raffleInfo[raffleIndex].prizes[prizeIndex];
if(prize.prizeType == PrizeType.ERC1155) {
ERC1155 prizeInstance = ERC1155(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId, 1, '');
} else {
ERC721 prizeInstance = ERC721(prize.tokenAddress);
prizeInstance.safeTransferFrom(address(this), winnerAddress, prize.tokenId);
}
raffleInfo[raffleIndex].prizes[prizeIndex].claimed = true;
emit PrizeClaimed(raffleIndex, prizeIndex, winnerAddress);
}
/**
* @dev Requests randomness from a user-provided seed
* @param raffleIndex The index of the Raffle to to require randomness for
* @param userProvidedSeed The seed provided by the Owner
* @return requestId (bytes32) the request id
*/
function getRandomNumber(
uint256 raffleIndex,
uint256 userProvidedSeed
)
internal
returns (bytes32 requestId)
{
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee, userProvidedSeed);
randomnessRequests[requestId] = raffleIndex;
raffleInfo[raffleIndex].randomResult = 1; // a flag for pending randomness
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator
* @notice MUST trigger WinnersDrafted event
* @param requestId The id of the request being fulfilled
* @param randomness The result of the randomness request
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
uint256 raffleIndex = randomnessRequests[requestId];
require(raffleInfo[raffleIndex].randomResult == 1, 'Raffle: Request already fulfilled');
raffleInfo[raffleIndex].randomResult = randomness;
emit WinnersDrafted(randomnessRequests[requestId], randomness);
}
/**
* @dev A simple time util
* @return (uint256) current block timestamp
*/
function now() internal view returns (uint256) {
return block.timestamp;
}
} | /// @title A provably fair NFT raffle
/// @author Valerio Leo @valerioHQ | NatSpecSingleLine | now | function now() internal view returns (uint256) {
return block.timestamp;
}
| /**
* @dev A simple time util
* @return (uint256) current block timestamp
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | {
"func_code_index": [
16629,
16707
]
} | 8,271 |
|
RocketFuelV2 | RocketFuelV2.sol | 0x6f8655032885e22268a74703b76b43db0acef582 | Solidity | RocketFuelV2 | contract RocketFuelV2 is Context, IERC20, Ownable {
using Address for address payable;
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;
mapping (address => bool) public allowedTransfer;
mapping (address => bool) isSniper;
address[] private _excluded;
bool public tradingEnabled = false;
bool public swapEnabled = true;
bool private swapping;
//Anti Dump
mapping(address => uint256) private _lastSell;
bool public coolDownEnabled = true;
uint256 public coolDownTime = 30 seconds;
modifier antiBot(address account){
require(tradingEnabled || allowedTransfer[account], "Trading not enabled yet");
_;
}
IRouter public router;
address public pair;
uint8 private constant _decimals = 9;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1e15 * 10**_decimals;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 public swapTokensAtAmount = 1_000_000_000_000 * 10**9;
uint256 public maxBuyLimit = 5_000_000_000_000 * 10**9;
uint256 public maxSellLimit = 5_000_000_000_000 * 10**9;
uint256 public maxWalletLimit = 20_000_000_000_000 * 10**9;
uint256 public genesis_block;
address marketingWallet;
address devWallet;
address buybackWallet;
string private constant _name = "Rocket Fuel V2";
string private constant _symbol = "RKTF";
struct Taxes {
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
Taxes public taxes = Taxes(2, 7, 0, 3, 0);
Taxes public sellTaxes = Taxes(2, 7, 3, 0, 0);
struct TotFeesPaidStruct{
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
TotFeesPaidStruct public totFeesPaid;
struct valuesFromGetValues{
uint256 rAmount;
uint256 rTransferAmount;
uint256 rRfi;
uint256 rMarketing;
uint256 rLiquidity;
uint256 rDev;
uint256 rBuyback;
uint256 tTransferAmount;
uint256 tRfi;
uint256 tMarketing;
uint256 tLiquidity;
uint256 tDev;
uint256 tBuyback;
}
event FeesChanged();
event UpdatedRouter(address oldRouter, address newRouter);
modifier lockTheSwap {
swapping = true;
_;
swapping = false;
}
constructor (address routerAddress) {
IRouter _router = IRouter(routerAddress);
address _pair = IFactory(_router.factory())
.createPair(address(this), _router.WETH());
router = _router;
pair = _pair;
excludeFromReward(pair);
_rOwned[owner()] = _rTotal;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[marketingWallet] = true;
_isExcludedFromFee[devWallet] = true;
_isExcludedFromFee[buybackWallet] = true;
allowedTransfer[address(this)] = true;
allowedTransfer[owner()] = true;
allowedTransfer[pair] = true;
allowedTransfer[marketingWallet] = true;
allowedTransfer[devWallet] = true;
allowedTransfer[buybackWallet] = true;
emit Transfer(address(0), owner(), _tTotal);
}
//std ERC20:
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
//override ERC20:
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 allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override antiBot(msg.sender) returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override antiBot(sender) returns (bool) {
require(!isSniper[sender], "Address is Sniper");
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public antiBot(msg.sender) returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public antiBot(msg.sender) returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function transfer(address recipient, uint256 amount) public override antiBot(msg.sender) returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tAmount, bool deductTransferRfi) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferRfi) {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rAmount;
} else {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount/currentRate;
}
//@dev kept original RFI naming -> "reward" as in reflection
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is not excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function launch() public onlyOwner{
tradingEnabled = true;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function setTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
taxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function setSellTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
sellTaxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function _reflectRfi(uint256 rRfi, uint256 tRfi) private {
_rTotal -=rRfi;
totFeesPaid.rfi +=tRfi;
}
function _takeLiquidity(uint256 rLiquidity, uint256 tLiquidity) private {
totFeesPaid.liquidity +=tLiquidity;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tLiquidity;
}
_rOwned[address(this)] +=rLiquidity;
}
function _takeMarketing(uint256 rMarketing, uint256 tMarketing) private {
totFeesPaid.marketing +=tMarketing;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tMarketing;
}
_rOwned[address(this)] +=rMarketing;
}
function _takeDev(uint256 rDev, uint256 tDev) private {
totFeesPaid.dev +=tDev;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tDev;
}
_rOwned[address(this)] +=rDev;
}
function _takeBuyback(uint256 rBuyback, uint256 tBuyback) private {
totFeesPaid.buyback +=tBuyback;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tBuyback;
}
_rOwned[address(this)] +=rBuyback;
}
function _getValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory to_return) {
to_return = _getTValues(tAmount, takeFee, isSell);
(to_return.rAmount, to_return.rTransferAmount, to_return.rRfi, to_return.rMarketing, to_return.rLiquidity) = _getRValues1(to_return, tAmount, takeFee, _getRate());
(to_return.rDev, to_return.rBuyback) = _getRValues2(to_return, takeFee, _getRate());
return to_return;
}
function _getTValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory s) {
if(!takeFee) {
s.tTransferAmount = tAmount;
return s;
}
Taxes memory temp;
if(isSell) temp = sellTaxes;
else temp = taxes;
s.tRfi = tAmount*temp.rfi/100;
s.tMarketing = tAmount*temp.marketing/100;
s.tLiquidity = tAmount*temp.liquidity/100;
s.tDev = tAmount*temp.dev/100;
s.tBuyback = tAmount*temp.buyback/100;
s.tTransferAmount = tAmount-s.tRfi-s.tMarketing-s.tLiquidity-s.tDev-s.tBuyback;
return s;
}
function _getRValues1(valuesFromGetValues memory s, uint256 tAmount, bool takeFee, uint256 currentRate) private pure returns (uint256 rAmount, uint256 rTransferAmount, uint256 rRfi,uint256 rMarketing, uint256 rLiquidity){
rAmount = tAmount*currentRate;
if(!takeFee) {
return(rAmount, rAmount, 0,0,0);
}
rRfi = s.tRfi*currentRate;
rMarketing = s.tMarketing*currentRate;
rLiquidity = s.tLiquidity*currentRate;
uint256 rDev = s.tDev*currentRate;
uint256 rBuyback = s.tBuyback*currentRate;
rTransferAmount = rAmount-rRfi-rMarketing-rLiquidity-rDev-rBuyback;
return (rAmount, rTransferAmount, rRfi,rMarketing,rLiquidity);
}
function _getRValues2(valuesFromGetValues memory s, bool takeFee, uint256 currentRate) private pure returns (uint256 rDev,uint256 rBuyback) {
if(!takeFee) {
return(0,0);
}
rDev = s.tDev*currentRate;
rBuyback = s.tBuyback*currentRate;
return (rDev,rBuyback);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply/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-_rOwned[_excluded[i]];
tSupply = tSupply-_tOwned[_excluded[i]];
}
if (rSupply < _rTotal/_tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from),"You are trying to transfer more than your balance");
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
require(tradingEnabled, "Trading not active");
}
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to] && block.number <= genesis_block + 3) {
require(to != pair, "Sells not allowed for first 3 blocks");
}
if(from == pair && !_isExcludedFromFee[to] && !swapping){
require(amount <= maxBuyLimit, "You are exceeding maxBuyLimit");
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(from != pair && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && !swapping){
require(amount <= maxSellLimit, "You are exceeding maxSellLimit");
if(to != pair){
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(coolDownEnabled){
uint256 timePassed = block.timestamp - _lastSell[from];
require(timePassed >= coolDownTime, "Cooldown enabled");
_lastSell[from] = block.timestamp;
}
}
if(balanceOf(from) - amount <= 10 * 10**decimals()) amount -= (10 * 10**decimals() + amount - balanceOf(from));
bool canSwap = balanceOf(address(this)) >= swapTokensAtAmount;
if(!swapping && swapEnabled && canSwap && from != pair && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
if(to == pair) swapAndLiquify(swapTokensAtAmount, sellTaxes);
else swapAndLiquify(swapTokensAtAmount, taxes);
}
bool takeFee = true;
bool isSell = false;
if(swapping || _isExcludedFromFee[from] || _isExcludedFromFee[to]) takeFee = false;
if(to == pair) isSell = true;
_tokenTransfer(from, to, amount, takeFee, isSell);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 tAmount, bool takeFee, bool isSell) private {
valuesFromGetValues memory s = _getValues(tAmount, takeFee, isSell);
if (_isExcluded[sender] ) { //from excluded
_tOwned[sender] = _tOwned[sender]-tAmount;
}
if (_isExcluded[recipient]) { //to excluded
_tOwned[recipient] = _tOwned[recipient]+s.tTransferAmount;
}
_rOwned[sender] = _rOwned[sender]-s.rAmount;
_rOwned[recipient] = _rOwned[recipient]+s.rTransferAmount;
if(s.rRfi > 0 || s.tRfi > 0) _reflectRfi(s.rRfi, s.tRfi);
if(s.rLiquidity > 0 || s.tLiquidity > 0) {
_takeLiquidity(s.rLiquidity,s.tLiquidity);
emit Transfer(sender, address(this), s.tLiquidity + s.tMarketing + s.tDev+ s.tBuyback);
}
if(s.rMarketing > 0 || s.tMarketing > 0) _takeMarketing(s.rMarketing, s.tMarketing);
if(s.rBuyback > 0 || s.tBuyback > 0) _takeBuyback(s.rBuyback, s.tBuyback);
if(s.rDev > 0 || s.tDev > 0) _takeDev(s.rDev, s.tDev);
emit Transfer(sender, recipient, s.tTransferAmount);
}
function swapAndLiquify(uint256 contractBalance, Taxes memory temp) private lockTheSwap{
uint256 denominator = (temp.liquidity + temp.marketing + temp.dev + temp.buyback) * 2;
uint256 tokensToAddLiquidityWith = contractBalance * temp.liquidity / denominator;
uint256 toSwap = contractBalance - tokensToAddLiquidityWith;
uint256 initialBalance = address(this).balance;
swapTokensForBNB(toSwap);
uint256 deltaBalance = address(this).balance - initialBalance;
uint256 unitBalance= deltaBalance / (denominator - temp.liquidity);
uint256 bnbToAddLiquidityWith = unitBalance * temp.liquidity;
if(bnbToAddLiquidityWith > 0){
// Add liquidity to pancake
addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith);
}
uint256 marketingAmt = unitBalance * 2 * temp.marketing;
if(marketingAmt > 0){
payable(marketingWallet).sendValue(marketingAmt);
}
uint256 devAmt = unitBalance * 2 * temp.dev;
if(devAmt > 0){
payable(devWallet).sendValue(devAmt);
}
uint256 buybackAmt = unitBalance * 2 * temp.buyback;
if(buybackAmt > 0){
payable(buybackWallet).sendValue(buybackAmt);
}
}
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(router), tokenAmount);
// add the liquidity
router.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function swapTokensForBNB(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function setIsSniper(address adr, bool sniper) external onlyOwner{
isSniper[adr] = sniper;
}
function bulkExcludeFee(address[] memory accounts, bool state) external onlyOwner{
for(uint256 i = 0; i < accounts.length; i++){
_isExcludedFromFee[accounts[i]] = state;
}
}
function updateMarketingWallet(address newWallet) external onlyOwner{
marketingWallet = newWallet;
}
function updateDevWallet(address newWallet) external onlyOwner{
devWallet = newWallet;
}
function updateBuybackWallet(address newWallet) external onlyOwner{
buybackWallet = newWallet;
}
function updateCooldown(bool state, uint256 time) external onlyOwner{
coolDownTime = time * 1 seconds;
coolDownEnabled = state;
}
function updateSwapTokensAtAmount(uint256 amount) external onlyOwner{
swapTokensAtAmount = amount * 10**_decimals;
}
function updateSwapEnabled(bool _enabled) external onlyOwner{
swapEnabled = _enabled;
}
function updateAllowedTransfer(address account, bool state) external onlyOwner{
allowedTransfer[account] = state;
}
function updateMaxTxLimit(uint256 maxBuy, uint256 maxSell) external onlyOwner{
maxBuyLimit = maxBuy * 10**decimals();
maxSellLimit = maxSell * 10**decimals();
}
function updateMaxWalletlimit(uint256 amount) external onlyOwner{
maxWalletLimit = amount * 10**decimals();
}
function updateRouterAndPair(address newRouter, address newPair) external onlyOwner{
router = IRouter(newRouter);
pair = newPair;
}
//Use this in case BNB are sent to the contract by mistake
function rescueBNB(uint256 weiAmount) external onlyOwner{
require(address(this).balance >= weiAmount, "insufficient BNB balance");
payable(msg.sender).transfer(weiAmount);
}
function rescueAnyBEP20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
IERC20(_tokenAddr).transfer(_to, _amount);
}
receive() external payable{
}
} | name | function name() public pure returns (string memory) {
return _name;
}
| //std ERC20: | LineComment | v0.8.7+commit.e28d00a7 | None | ipfs://da73f3f16b109b70329266f2661ff6afbd2a2b9bd4661a751b78d4f9ee193a54 | {
"func_code_index": [
3704,
3792
]
} | 8,272 |
||
RocketFuelV2 | RocketFuelV2.sol | 0x6f8655032885e22268a74703b76b43db0acef582 | Solidity | RocketFuelV2 | contract RocketFuelV2 is Context, IERC20, Ownable {
using Address for address payable;
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;
mapping (address => bool) public allowedTransfer;
mapping (address => bool) isSniper;
address[] private _excluded;
bool public tradingEnabled = false;
bool public swapEnabled = true;
bool private swapping;
//Anti Dump
mapping(address => uint256) private _lastSell;
bool public coolDownEnabled = true;
uint256 public coolDownTime = 30 seconds;
modifier antiBot(address account){
require(tradingEnabled || allowedTransfer[account], "Trading not enabled yet");
_;
}
IRouter public router;
address public pair;
uint8 private constant _decimals = 9;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1e15 * 10**_decimals;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 public swapTokensAtAmount = 1_000_000_000_000 * 10**9;
uint256 public maxBuyLimit = 5_000_000_000_000 * 10**9;
uint256 public maxSellLimit = 5_000_000_000_000 * 10**9;
uint256 public maxWalletLimit = 20_000_000_000_000 * 10**9;
uint256 public genesis_block;
address marketingWallet;
address devWallet;
address buybackWallet;
string private constant _name = "Rocket Fuel V2";
string private constant _symbol = "RKTF";
struct Taxes {
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
Taxes public taxes = Taxes(2, 7, 0, 3, 0);
Taxes public sellTaxes = Taxes(2, 7, 3, 0, 0);
struct TotFeesPaidStruct{
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
TotFeesPaidStruct public totFeesPaid;
struct valuesFromGetValues{
uint256 rAmount;
uint256 rTransferAmount;
uint256 rRfi;
uint256 rMarketing;
uint256 rLiquidity;
uint256 rDev;
uint256 rBuyback;
uint256 tTransferAmount;
uint256 tRfi;
uint256 tMarketing;
uint256 tLiquidity;
uint256 tDev;
uint256 tBuyback;
}
event FeesChanged();
event UpdatedRouter(address oldRouter, address newRouter);
modifier lockTheSwap {
swapping = true;
_;
swapping = false;
}
constructor (address routerAddress) {
IRouter _router = IRouter(routerAddress);
address _pair = IFactory(_router.factory())
.createPair(address(this), _router.WETH());
router = _router;
pair = _pair;
excludeFromReward(pair);
_rOwned[owner()] = _rTotal;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[marketingWallet] = true;
_isExcludedFromFee[devWallet] = true;
_isExcludedFromFee[buybackWallet] = true;
allowedTransfer[address(this)] = true;
allowedTransfer[owner()] = true;
allowedTransfer[pair] = true;
allowedTransfer[marketingWallet] = true;
allowedTransfer[devWallet] = true;
allowedTransfer[buybackWallet] = true;
emit Transfer(address(0), owner(), _tTotal);
}
//std ERC20:
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
//override ERC20:
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 allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override antiBot(msg.sender) returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override antiBot(sender) returns (bool) {
require(!isSniper[sender], "Address is Sniper");
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public antiBot(msg.sender) returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public antiBot(msg.sender) returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function transfer(address recipient, uint256 amount) public override antiBot(msg.sender) returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tAmount, bool deductTransferRfi) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferRfi) {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rAmount;
} else {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount/currentRate;
}
//@dev kept original RFI naming -> "reward" as in reflection
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is not excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function launch() public onlyOwner{
tradingEnabled = true;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function setTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
taxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function setSellTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
sellTaxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function _reflectRfi(uint256 rRfi, uint256 tRfi) private {
_rTotal -=rRfi;
totFeesPaid.rfi +=tRfi;
}
function _takeLiquidity(uint256 rLiquidity, uint256 tLiquidity) private {
totFeesPaid.liquidity +=tLiquidity;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tLiquidity;
}
_rOwned[address(this)] +=rLiquidity;
}
function _takeMarketing(uint256 rMarketing, uint256 tMarketing) private {
totFeesPaid.marketing +=tMarketing;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tMarketing;
}
_rOwned[address(this)] +=rMarketing;
}
function _takeDev(uint256 rDev, uint256 tDev) private {
totFeesPaid.dev +=tDev;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tDev;
}
_rOwned[address(this)] +=rDev;
}
function _takeBuyback(uint256 rBuyback, uint256 tBuyback) private {
totFeesPaid.buyback +=tBuyback;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tBuyback;
}
_rOwned[address(this)] +=rBuyback;
}
function _getValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory to_return) {
to_return = _getTValues(tAmount, takeFee, isSell);
(to_return.rAmount, to_return.rTransferAmount, to_return.rRfi, to_return.rMarketing, to_return.rLiquidity) = _getRValues1(to_return, tAmount, takeFee, _getRate());
(to_return.rDev, to_return.rBuyback) = _getRValues2(to_return, takeFee, _getRate());
return to_return;
}
function _getTValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory s) {
if(!takeFee) {
s.tTransferAmount = tAmount;
return s;
}
Taxes memory temp;
if(isSell) temp = sellTaxes;
else temp = taxes;
s.tRfi = tAmount*temp.rfi/100;
s.tMarketing = tAmount*temp.marketing/100;
s.tLiquidity = tAmount*temp.liquidity/100;
s.tDev = tAmount*temp.dev/100;
s.tBuyback = tAmount*temp.buyback/100;
s.tTransferAmount = tAmount-s.tRfi-s.tMarketing-s.tLiquidity-s.tDev-s.tBuyback;
return s;
}
function _getRValues1(valuesFromGetValues memory s, uint256 tAmount, bool takeFee, uint256 currentRate) private pure returns (uint256 rAmount, uint256 rTransferAmount, uint256 rRfi,uint256 rMarketing, uint256 rLiquidity){
rAmount = tAmount*currentRate;
if(!takeFee) {
return(rAmount, rAmount, 0,0,0);
}
rRfi = s.tRfi*currentRate;
rMarketing = s.tMarketing*currentRate;
rLiquidity = s.tLiquidity*currentRate;
uint256 rDev = s.tDev*currentRate;
uint256 rBuyback = s.tBuyback*currentRate;
rTransferAmount = rAmount-rRfi-rMarketing-rLiquidity-rDev-rBuyback;
return (rAmount, rTransferAmount, rRfi,rMarketing,rLiquidity);
}
function _getRValues2(valuesFromGetValues memory s, bool takeFee, uint256 currentRate) private pure returns (uint256 rDev,uint256 rBuyback) {
if(!takeFee) {
return(0,0);
}
rDev = s.tDev*currentRate;
rBuyback = s.tBuyback*currentRate;
return (rDev,rBuyback);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply/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-_rOwned[_excluded[i]];
tSupply = tSupply-_tOwned[_excluded[i]];
}
if (rSupply < _rTotal/_tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from),"You are trying to transfer more than your balance");
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
require(tradingEnabled, "Trading not active");
}
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to] && block.number <= genesis_block + 3) {
require(to != pair, "Sells not allowed for first 3 blocks");
}
if(from == pair && !_isExcludedFromFee[to] && !swapping){
require(amount <= maxBuyLimit, "You are exceeding maxBuyLimit");
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(from != pair && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && !swapping){
require(amount <= maxSellLimit, "You are exceeding maxSellLimit");
if(to != pair){
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(coolDownEnabled){
uint256 timePassed = block.timestamp - _lastSell[from];
require(timePassed >= coolDownTime, "Cooldown enabled");
_lastSell[from] = block.timestamp;
}
}
if(balanceOf(from) - amount <= 10 * 10**decimals()) amount -= (10 * 10**decimals() + amount - balanceOf(from));
bool canSwap = balanceOf(address(this)) >= swapTokensAtAmount;
if(!swapping && swapEnabled && canSwap && from != pair && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
if(to == pair) swapAndLiquify(swapTokensAtAmount, sellTaxes);
else swapAndLiquify(swapTokensAtAmount, taxes);
}
bool takeFee = true;
bool isSell = false;
if(swapping || _isExcludedFromFee[from] || _isExcludedFromFee[to]) takeFee = false;
if(to == pair) isSell = true;
_tokenTransfer(from, to, amount, takeFee, isSell);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 tAmount, bool takeFee, bool isSell) private {
valuesFromGetValues memory s = _getValues(tAmount, takeFee, isSell);
if (_isExcluded[sender] ) { //from excluded
_tOwned[sender] = _tOwned[sender]-tAmount;
}
if (_isExcluded[recipient]) { //to excluded
_tOwned[recipient] = _tOwned[recipient]+s.tTransferAmount;
}
_rOwned[sender] = _rOwned[sender]-s.rAmount;
_rOwned[recipient] = _rOwned[recipient]+s.rTransferAmount;
if(s.rRfi > 0 || s.tRfi > 0) _reflectRfi(s.rRfi, s.tRfi);
if(s.rLiquidity > 0 || s.tLiquidity > 0) {
_takeLiquidity(s.rLiquidity,s.tLiquidity);
emit Transfer(sender, address(this), s.tLiquidity + s.tMarketing + s.tDev+ s.tBuyback);
}
if(s.rMarketing > 0 || s.tMarketing > 0) _takeMarketing(s.rMarketing, s.tMarketing);
if(s.rBuyback > 0 || s.tBuyback > 0) _takeBuyback(s.rBuyback, s.tBuyback);
if(s.rDev > 0 || s.tDev > 0) _takeDev(s.rDev, s.tDev);
emit Transfer(sender, recipient, s.tTransferAmount);
}
function swapAndLiquify(uint256 contractBalance, Taxes memory temp) private lockTheSwap{
uint256 denominator = (temp.liquidity + temp.marketing + temp.dev + temp.buyback) * 2;
uint256 tokensToAddLiquidityWith = contractBalance * temp.liquidity / denominator;
uint256 toSwap = contractBalance - tokensToAddLiquidityWith;
uint256 initialBalance = address(this).balance;
swapTokensForBNB(toSwap);
uint256 deltaBalance = address(this).balance - initialBalance;
uint256 unitBalance= deltaBalance / (denominator - temp.liquidity);
uint256 bnbToAddLiquidityWith = unitBalance * temp.liquidity;
if(bnbToAddLiquidityWith > 0){
// Add liquidity to pancake
addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith);
}
uint256 marketingAmt = unitBalance * 2 * temp.marketing;
if(marketingAmt > 0){
payable(marketingWallet).sendValue(marketingAmt);
}
uint256 devAmt = unitBalance * 2 * temp.dev;
if(devAmt > 0){
payable(devWallet).sendValue(devAmt);
}
uint256 buybackAmt = unitBalance * 2 * temp.buyback;
if(buybackAmt > 0){
payable(buybackWallet).sendValue(buybackAmt);
}
}
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(router), tokenAmount);
// add the liquidity
router.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function swapTokensForBNB(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function setIsSniper(address adr, bool sniper) external onlyOwner{
isSniper[adr] = sniper;
}
function bulkExcludeFee(address[] memory accounts, bool state) external onlyOwner{
for(uint256 i = 0; i < accounts.length; i++){
_isExcludedFromFee[accounts[i]] = state;
}
}
function updateMarketingWallet(address newWallet) external onlyOwner{
marketingWallet = newWallet;
}
function updateDevWallet(address newWallet) external onlyOwner{
devWallet = newWallet;
}
function updateBuybackWallet(address newWallet) external onlyOwner{
buybackWallet = newWallet;
}
function updateCooldown(bool state, uint256 time) external onlyOwner{
coolDownTime = time * 1 seconds;
coolDownEnabled = state;
}
function updateSwapTokensAtAmount(uint256 amount) external onlyOwner{
swapTokensAtAmount = amount * 10**_decimals;
}
function updateSwapEnabled(bool _enabled) external onlyOwner{
swapEnabled = _enabled;
}
function updateAllowedTransfer(address account, bool state) external onlyOwner{
allowedTransfer[account] = state;
}
function updateMaxTxLimit(uint256 maxBuy, uint256 maxSell) external onlyOwner{
maxBuyLimit = maxBuy * 10**decimals();
maxSellLimit = maxSell * 10**decimals();
}
function updateMaxWalletlimit(uint256 amount) external onlyOwner{
maxWalletLimit = amount * 10**decimals();
}
function updateRouterAndPair(address newRouter, address newPair) external onlyOwner{
router = IRouter(newRouter);
pair = newPair;
}
//Use this in case BNB are sent to the contract by mistake
function rescueBNB(uint256 weiAmount) external onlyOwner{
require(address(this).balance >= weiAmount, "insufficient BNB balance");
payable(msg.sender).transfer(weiAmount);
}
function rescueAnyBEP20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
IERC20(_tokenAddr).transfer(_to, _amount);
}
receive() external payable{
}
} | totalSupply | function totalSupply() public view override returns (uint256) {
return _tTotal;
}
| //override ERC20: | LineComment | v0.8.7+commit.e28d00a7 | None | ipfs://da73f3f16b109b70329266f2661ff6afbd2a2b9bd4661a751b78d4f9ee193a54 | {
"func_code_index": [
4000,
4100
]
} | 8,273 |
||
RocketFuelV2 | RocketFuelV2.sol | 0x6f8655032885e22268a74703b76b43db0acef582 | Solidity | RocketFuelV2 | contract RocketFuelV2 is Context, IERC20, Ownable {
using Address for address payable;
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;
mapping (address => bool) public allowedTransfer;
mapping (address => bool) isSniper;
address[] private _excluded;
bool public tradingEnabled = false;
bool public swapEnabled = true;
bool private swapping;
//Anti Dump
mapping(address => uint256) private _lastSell;
bool public coolDownEnabled = true;
uint256 public coolDownTime = 30 seconds;
modifier antiBot(address account){
require(tradingEnabled || allowedTransfer[account], "Trading not enabled yet");
_;
}
IRouter public router;
address public pair;
uint8 private constant _decimals = 9;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1e15 * 10**_decimals;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 public swapTokensAtAmount = 1_000_000_000_000 * 10**9;
uint256 public maxBuyLimit = 5_000_000_000_000 * 10**9;
uint256 public maxSellLimit = 5_000_000_000_000 * 10**9;
uint256 public maxWalletLimit = 20_000_000_000_000 * 10**9;
uint256 public genesis_block;
address marketingWallet;
address devWallet;
address buybackWallet;
string private constant _name = "Rocket Fuel V2";
string private constant _symbol = "RKTF";
struct Taxes {
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
Taxes public taxes = Taxes(2, 7, 0, 3, 0);
Taxes public sellTaxes = Taxes(2, 7, 3, 0, 0);
struct TotFeesPaidStruct{
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
TotFeesPaidStruct public totFeesPaid;
struct valuesFromGetValues{
uint256 rAmount;
uint256 rTransferAmount;
uint256 rRfi;
uint256 rMarketing;
uint256 rLiquidity;
uint256 rDev;
uint256 rBuyback;
uint256 tTransferAmount;
uint256 tRfi;
uint256 tMarketing;
uint256 tLiquidity;
uint256 tDev;
uint256 tBuyback;
}
event FeesChanged();
event UpdatedRouter(address oldRouter, address newRouter);
modifier lockTheSwap {
swapping = true;
_;
swapping = false;
}
constructor (address routerAddress) {
IRouter _router = IRouter(routerAddress);
address _pair = IFactory(_router.factory())
.createPair(address(this), _router.WETH());
router = _router;
pair = _pair;
excludeFromReward(pair);
_rOwned[owner()] = _rTotal;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[marketingWallet] = true;
_isExcludedFromFee[devWallet] = true;
_isExcludedFromFee[buybackWallet] = true;
allowedTransfer[address(this)] = true;
allowedTransfer[owner()] = true;
allowedTransfer[pair] = true;
allowedTransfer[marketingWallet] = true;
allowedTransfer[devWallet] = true;
allowedTransfer[buybackWallet] = true;
emit Transfer(address(0), owner(), _tTotal);
}
//std ERC20:
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
//override ERC20:
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 allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override antiBot(msg.sender) returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override antiBot(sender) returns (bool) {
require(!isSniper[sender], "Address is Sniper");
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public antiBot(msg.sender) returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public antiBot(msg.sender) returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function transfer(address recipient, uint256 amount) public override antiBot(msg.sender) returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tAmount, bool deductTransferRfi) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferRfi) {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rAmount;
} else {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount/currentRate;
}
//@dev kept original RFI naming -> "reward" as in reflection
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is not excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function launch() public onlyOwner{
tradingEnabled = true;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function setTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
taxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function setSellTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
sellTaxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function _reflectRfi(uint256 rRfi, uint256 tRfi) private {
_rTotal -=rRfi;
totFeesPaid.rfi +=tRfi;
}
function _takeLiquidity(uint256 rLiquidity, uint256 tLiquidity) private {
totFeesPaid.liquidity +=tLiquidity;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tLiquidity;
}
_rOwned[address(this)] +=rLiquidity;
}
function _takeMarketing(uint256 rMarketing, uint256 tMarketing) private {
totFeesPaid.marketing +=tMarketing;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tMarketing;
}
_rOwned[address(this)] +=rMarketing;
}
function _takeDev(uint256 rDev, uint256 tDev) private {
totFeesPaid.dev +=tDev;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tDev;
}
_rOwned[address(this)] +=rDev;
}
function _takeBuyback(uint256 rBuyback, uint256 tBuyback) private {
totFeesPaid.buyback +=tBuyback;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tBuyback;
}
_rOwned[address(this)] +=rBuyback;
}
function _getValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory to_return) {
to_return = _getTValues(tAmount, takeFee, isSell);
(to_return.rAmount, to_return.rTransferAmount, to_return.rRfi, to_return.rMarketing, to_return.rLiquidity) = _getRValues1(to_return, tAmount, takeFee, _getRate());
(to_return.rDev, to_return.rBuyback) = _getRValues2(to_return, takeFee, _getRate());
return to_return;
}
function _getTValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory s) {
if(!takeFee) {
s.tTransferAmount = tAmount;
return s;
}
Taxes memory temp;
if(isSell) temp = sellTaxes;
else temp = taxes;
s.tRfi = tAmount*temp.rfi/100;
s.tMarketing = tAmount*temp.marketing/100;
s.tLiquidity = tAmount*temp.liquidity/100;
s.tDev = tAmount*temp.dev/100;
s.tBuyback = tAmount*temp.buyback/100;
s.tTransferAmount = tAmount-s.tRfi-s.tMarketing-s.tLiquidity-s.tDev-s.tBuyback;
return s;
}
function _getRValues1(valuesFromGetValues memory s, uint256 tAmount, bool takeFee, uint256 currentRate) private pure returns (uint256 rAmount, uint256 rTransferAmount, uint256 rRfi,uint256 rMarketing, uint256 rLiquidity){
rAmount = tAmount*currentRate;
if(!takeFee) {
return(rAmount, rAmount, 0,0,0);
}
rRfi = s.tRfi*currentRate;
rMarketing = s.tMarketing*currentRate;
rLiquidity = s.tLiquidity*currentRate;
uint256 rDev = s.tDev*currentRate;
uint256 rBuyback = s.tBuyback*currentRate;
rTransferAmount = rAmount-rRfi-rMarketing-rLiquidity-rDev-rBuyback;
return (rAmount, rTransferAmount, rRfi,rMarketing,rLiquidity);
}
function _getRValues2(valuesFromGetValues memory s, bool takeFee, uint256 currentRate) private pure returns (uint256 rDev,uint256 rBuyback) {
if(!takeFee) {
return(0,0);
}
rDev = s.tDev*currentRate;
rBuyback = s.tBuyback*currentRate;
return (rDev,rBuyback);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply/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-_rOwned[_excluded[i]];
tSupply = tSupply-_tOwned[_excluded[i]];
}
if (rSupply < _rTotal/_tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from),"You are trying to transfer more than your balance");
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
require(tradingEnabled, "Trading not active");
}
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to] && block.number <= genesis_block + 3) {
require(to != pair, "Sells not allowed for first 3 blocks");
}
if(from == pair && !_isExcludedFromFee[to] && !swapping){
require(amount <= maxBuyLimit, "You are exceeding maxBuyLimit");
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(from != pair && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && !swapping){
require(amount <= maxSellLimit, "You are exceeding maxSellLimit");
if(to != pair){
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(coolDownEnabled){
uint256 timePassed = block.timestamp - _lastSell[from];
require(timePassed >= coolDownTime, "Cooldown enabled");
_lastSell[from] = block.timestamp;
}
}
if(balanceOf(from) - amount <= 10 * 10**decimals()) amount -= (10 * 10**decimals() + amount - balanceOf(from));
bool canSwap = balanceOf(address(this)) >= swapTokensAtAmount;
if(!swapping && swapEnabled && canSwap && from != pair && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
if(to == pair) swapAndLiquify(swapTokensAtAmount, sellTaxes);
else swapAndLiquify(swapTokensAtAmount, taxes);
}
bool takeFee = true;
bool isSell = false;
if(swapping || _isExcludedFromFee[from] || _isExcludedFromFee[to]) takeFee = false;
if(to == pair) isSell = true;
_tokenTransfer(from, to, amount, takeFee, isSell);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 tAmount, bool takeFee, bool isSell) private {
valuesFromGetValues memory s = _getValues(tAmount, takeFee, isSell);
if (_isExcluded[sender] ) { //from excluded
_tOwned[sender] = _tOwned[sender]-tAmount;
}
if (_isExcluded[recipient]) { //to excluded
_tOwned[recipient] = _tOwned[recipient]+s.tTransferAmount;
}
_rOwned[sender] = _rOwned[sender]-s.rAmount;
_rOwned[recipient] = _rOwned[recipient]+s.rTransferAmount;
if(s.rRfi > 0 || s.tRfi > 0) _reflectRfi(s.rRfi, s.tRfi);
if(s.rLiquidity > 0 || s.tLiquidity > 0) {
_takeLiquidity(s.rLiquidity,s.tLiquidity);
emit Transfer(sender, address(this), s.tLiquidity + s.tMarketing + s.tDev+ s.tBuyback);
}
if(s.rMarketing > 0 || s.tMarketing > 0) _takeMarketing(s.rMarketing, s.tMarketing);
if(s.rBuyback > 0 || s.tBuyback > 0) _takeBuyback(s.rBuyback, s.tBuyback);
if(s.rDev > 0 || s.tDev > 0) _takeDev(s.rDev, s.tDev);
emit Transfer(sender, recipient, s.tTransferAmount);
}
function swapAndLiquify(uint256 contractBalance, Taxes memory temp) private lockTheSwap{
uint256 denominator = (temp.liquidity + temp.marketing + temp.dev + temp.buyback) * 2;
uint256 tokensToAddLiquidityWith = contractBalance * temp.liquidity / denominator;
uint256 toSwap = contractBalance - tokensToAddLiquidityWith;
uint256 initialBalance = address(this).balance;
swapTokensForBNB(toSwap);
uint256 deltaBalance = address(this).balance - initialBalance;
uint256 unitBalance= deltaBalance / (denominator - temp.liquidity);
uint256 bnbToAddLiquidityWith = unitBalance * temp.liquidity;
if(bnbToAddLiquidityWith > 0){
// Add liquidity to pancake
addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith);
}
uint256 marketingAmt = unitBalance * 2 * temp.marketing;
if(marketingAmt > 0){
payable(marketingWallet).sendValue(marketingAmt);
}
uint256 devAmt = unitBalance * 2 * temp.dev;
if(devAmt > 0){
payable(devWallet).sendValue(devAmt);
}
uint256 buybackAmt = unitBalance * 2 * temp.buyback;
if(buybackAmt > 0){
payable(buybackWallet).sendValue(buybackAmt);
}
}
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(router), tokenAmount);
// add the liquidity
router.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function swapTokensForBNB(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function setIsSniper(address adr, bool sniper) external onlyOwner{
isSniper[adr] = sniper;
}
function bulkExcludeFee(address[] memory accounts, bool state) external onlyOwner{
for(uint256 i = 0; i < accounts.length; i++){
_isExcludedFromFee[accounts[i]] = state;
}
}
function updateMarketingWallet(address newWallet) external onlyOwner{
marketingWallet = newWallet;
}
function updateDevWallet(address newWallet) external onlyOwner{
devWallet = newWallet;
}
function updateBuybackWallet(address newWallet) external onlyOwner{
buybackWallet = newWallet;
}
function updateCooldown(bool state, uint256 time) external onlyOwner{
coolDownTime = time * 1 seconds;
coolDownEnabled = state;
}
function updateSwapTokensAtAmount(uint256 amount) external onlyOwner{
swapTokensAtAmount = amount * 10**_decimals;
}
function updateSwapEnabled(bool _enabled) external onlyOwner{
swapEnabled = _enabled;
}
function updateAllowedTransfer(address account, bool state) external onlyOwner{
allowedTransfer[account] = state;
}
function updateMaxTxLimit(uint256 maxBuy, uint256 maxSell) external onlyOwner{
maxBuyLimit = maxBuy * 10**decimals();
maxSellLimit = maxSell * 10**decimals();
}
function updateMaxWalletlimit(uint256 amount) external onlyOwner{
maxWalletLimit = amount * 10**decimals();
}
function updateRouterAndPair(address newRouter, address newPair) external onlyOwner{
router = IRouter(newRouter);
pair = newPair;
}
//Use this in case BNB are sent to the contract by mistake
function rescueBNB(uint256 weiAmount) external onlyOwner{
require(address(this).balance >= weiAmount, "insufficient BNB balance");
payable(msg.sender).transfer(weiAmount);
}
function rescueAnyBEP20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
IERC20(_tokenAddr).transfer(_to, _amount);
}
receive() external payable{
}
} | excludeFromReward | function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
| //@dev kept original RFI naming -> "reward" as in reflection | LineComment | v0.8.7+commit.e28d00a7 | None | ipfs://da73f3f16b109b70329266f2661ff6afbd2a2b9bd4661a751b78d4f9ee193a54 | {
"func_code_index": [
6928,
7266
]
} | 8,274 |
||
RocketFuelV2 | RocketFuelV2.sol | 0x6f8655032885e22268a74703b76b43db0acef582 | Solidity | RocketFuelV2 | contract RocketFuelV2 is Context, IERC20, Ownable {
using Address for address payable;
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;
mapping (address => bool) public allowedTransfer;
mapping (address => bool) isSniper;
address[] private _excluded;
bool public tradingEnabled = false;
bool public swapEnabled = true;
bool private swapping;
//Anti Dump
mapping(address => uint256) private _lastSell;
bool public coolDownEnabled = true;
uint256 public coolDownTime = 30 seconds;
modifier antiBot(address account){
require(tradingEnabled || allowedTransfer[account], "Trading not enabled yet");
_;
}
IRouter public router;
address public pair;
uint8 private constant _decimals = 9;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1e15 * 10**_decimals;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 public swapTokensAtAmount = 1_000_000_000_000 * 10**9;
uint256 public maxBuyLimit = 5_000_000_000_000 * 10**9;
uint256 public maxSellLimit = 5_000_000_000_000 * 10**9;
uint256 public maxWalletLimit = 20_000_000_000_000 * 10**9;
uint256 public genesis_block;
address marketingWallet;
address devWallet;
address buybackWallet;
string private constant _name = "Rocket Fuel V2";
string private constant _symbol = "RKTF";
struct Taxes {
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
Taxes public taxes = Taxes(2, 7, 0, 3, 0);
Taxes public sellTaxes = Taxes(2, 7, 3, 0, 0);
struct TotFeesPaidStruct{
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
TotFeesPaidStruct public totFeesPaid;
struct valuesFromGetValues{
uint256 rAmount;
uint256 rTransferAmount;
uint256 rRfi;
uint256 rMarketing;
uint256 rLiquidity;
uint256 rDev;
uint256 rBuyback;
uint256 tTransferAmount;
uint256 tRfi;
uint256 tMarketing;
uint256 tLiquidity;
uint256 tDev;
uint256 tBuyback;
}
event FeesChanged();
event UpdatedRouter(address oldRouter, address newRouter);
modifier lockTheSwap {
swapping = true;
_;
swapping = false;
}
constructor (address routerAddress) {
IRouter _router = IRouter(routerAddress);
address _pair = IFactory(_router.factory())
.createPair(address(this), _router.WETH());
router = _router;
pair = _pair;
excludeFromReward(pair);
_rOwned[owner()] = _rTotal;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[marketingWallet] = true;
_isExcludedFromFee[devWallet] = true;
_isExcludedFromFee[buybackWallet] = true;
allowedTransfer[address(this)] = true;
allowedTransfer[owner()] = true;
allowedTransfer[pair] = true;
allowedTransfer[marketingWallet] = true;
allowedTransfer[devWallet] = true;
allowedTransfer[buybackWallet] = true;
emit Transfer(address(0), owner(), _tTotal);
}
//std ERC20:
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
//override ERC20:
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 allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override antiBot(msg.sender) returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override antiBot(sender) returns (bool) {
require(!isSniper[sender], "Address is Sniper");
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public antiBot(msg.sender) returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public antiBot(msg.sender) returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function transfer(address recipient, uint256 amount) public override antiBot(msg.sender) returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tAmount, bool deductTransferRfi) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferRfi) {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rAmount;
} else {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount/currentRate;
}
//@dev kept original RFI naming -> "reward" as in reflection
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is not excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function launch() public onlyOwner{
tradingEnabled = true;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function setTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
taxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function setSellTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
sellTaxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function _reflectRfi(uint256 rRfi, uint256 tRfi) private {
_rTotal -=rRfi;
totFeesPaid.rfi +=tRfi;
}
function _takeLiquidity(uint256 rLiquidity, uint256 tLiquidity) private {
totFeesPaid.liquidity +=tLiquidity;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tLiquidity;
}
_rOwned[address(this)] +=rLiquidity;
}
function _takeMarketing(uint256 rMarketing, uint256 tMarketing) private {
totFeesPaid.marketing +=tMarketing;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tMarketing;
}
_rOwned[address(this)] +=rMarketing;
}
function _takeDev(uint256 rDev, uint256 tDev) private {
totFeesPaid.dev +=tDev;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tDev;
}
_rOwned[address(this)] +=rDev;
}
function _takeBuyback(uint256 rBuyback, uint256 tBuyback) private {
totFeesPaid.buyback +=tBuyback;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tBuyback;
}
_rOwned[address(this)] +=rBuyback;
}
function _getValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory to_return) {
to_return = _getTValues(tAmount, takeFee, isSell);
(to_return.rAmount, to_return.rTransferAmount, to_return.rRfi, to_return.rMarketing, to_return.rLiquidity) = _getRValues1(to_return, tAmount, takeFee, _getRate());
(to_return.rDev, to_return.rBuyback) = _getRValues2(to_return, takeFee, _getRate());
return to_return;
}
function _getTValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory s) {
if(!takeFee) {
s.tTransferAmount = tAmount;
return s;
}
Taxes memory temp;
if(isSell) temp = sellTaxes;
else temp = taxes;
s.tRfi = tAmount*temp.rfi/100;
s.tMarketing = tAmount*temp.marketing/100;
s.tLiquidity = tAmount*temp.liquidity/100;
s.tDev = tAmount*temp.dev/100;
s.tBuyback = tAmount*temp.buyback/100;
s.tTransferAmount = tAmount-s.tRfi-s.tMarketing-s.tLiquidity-s.tDev-s.tBuyback;
return s;
}
function _getRValues1(valuesFromGetValues memory s, uint256 tAmount, bool takeFee, uint256 currentRate) private pure returns (uint256 rAmount, uint256 rTransferAmount, uint256 rRfi,uint256 rMarketing, uint256 rLiquidity){
rAmount = tAmount*currentRate;
if(!takeFee) {
return(rAmount, rAmount, 0,0,0);
}
rRfi = s.tRfi*currentRate;
rMarketing = s.tMarketing*currentRate;
rLiquidity = s.tLiquidity*currentRate;
uint256 rDev = s.tDev*currentRate;
uint256 rBuyback = s.tBuyback*currentRate;
rTransferAmount = rAmount-rRfi-rMarketing-rLiquidity-rDev-rBuyback;
return (rAmount, rTransferAmount, rRfi,rMarketing,rLiquidity);
}
function _getRValues2(valuesFromGetValues memory s, bool takeFee, uint256 currentRate) private pure returns (uint256 rDev,uint256 rBuyback) {
if(!takeFee) {
return(0,0);
}
rDev = s.tDev*currentRate;
rBuyback = s.tBuyback*currentRate;
return (rDev,rBuyback);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply/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-_rOwned[_excluded[i]];
tSupply = tSupply-_tOwned[_excluded[i]];
}
if (rSupply < _rTotal/_tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from),"You are trying to transfer more than your balance");
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
require(tradingEnabled, "Trading not active");
}
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to] && block.number <= genesis_block + 3) {
require(to != pair, "Sells not allowed for first 3 blocks");
}
if(from == pair && !_isExcludedFromFee[to] && !swapping){
require(amount <= maxBuyLimit, "You are exceeding maxBuyLimit");
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(from != pair && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && !swapping){
require(amount <= maxSellLimit, "You are exceeding maxSellLimit");
if(to != pair){
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(coolDownEnabled){
uint256 timePassed = block.timestamp - _lastSell[from];
require(timePassed >= coolDownTime, "Cooldown enabled");
_lastSell[from] = block.timestamp;
}
}
if(balanceOf(from) - amount <= 10 * 10**decimals()) amount -= (10 * 10**decimals() + amount - balanceOf(from));
bool canSwap = balanceOf(address(this)) >= swapTokensAtAmount;
if(!swapping && swapEnabled && canSwap && from != pair && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
if(to == pair) swapAndLiquify(swapTokensAtAmount, sellTaxes);
else swapAndLiquify(swapTokensAtAmount, taxes);
}
bool takeFee = true;
bool isSell = false;
if(swapping || _isExcludedFromFee[from] || _isExcludedFromFee[to]) takeFee = false;
if(to == pair) isSell = true;
_tokenTransfer(from, to, amount, takeFee, isSell);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 tAmount, bool takeFee, bool isSell) private {
valuesFromGetValues memory s = _getValues(tAmount, takeFee, isSell);
if (_isExcluded[sender] ) { //from excluded
_tOwned[sender] = _tOwned[sender]-tAmount;
}
if (_isExcluded[recipient]) { //to excluded
_tOwned[recipient] = _tOwned[recipient]+s.tTransferAmount;
}
_rOwned[sender] = _rOwned[sender]-s.rAmount;
_rOwned[recipient] = _rOwned[recipient]+s.rTransferAmount;
if(s.rRfi > 0 || s.tRfi > 0) _reflectRfi(s.rRfi, s.tRfi);
if(s.rLiquidity > 0 || s.tLiquidity > 0) {
_takeLiquidity(s.rLiquidity,s.tLiquidity);
emit Transfer(sender, address(this), s.tLiquidity + s.tMarketing + s.tDev+ s.tBuyback);
}
if(s.rMarketing > 0 || s.tMarketing > 0) _takeMarketing(s.rMarketing, s.tMarketing);
if(s.rBuyback > 0 || s.tBuyback > 0) _takeBuyback(s.rBuyback, s.tBuyback);
if(s.rDev > 0 || s.tDev > 0) _takeDev(s.rDev, s.tDev);
emit Transfer(sender, recipient, s.tTransferAmount);
}
function swapAndLiquify(uint256 contractBalance, Taxes memory temp) private lockTheSwap{
uint256 denominator = (temp.liquidity + temp.marketing + temp.dev + temp.buyback) * 2;
uint256 tokensToAddLiquidityWith = contractBalance * temp.liquidity / denominator;
uint256 toSwap = contractBalance - tokensToAddLiquidityWith;
uint256 initialBalance = address(this).balance;
swapTokensForBNB(toSwap);
uint256 deltaBalance = address(this).balance - initialBalance;
uint256 unitBalance= deltaBalance / (denominator - temp.liquidity);
uint256 bnbToAddLiquidityWith = unitBalance * temp.liquidity;
if(bnbToAddLiquidityWith > 0){
// Add liquidity to pancake
addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith);
}
uint256 marketingAmt = unitBalance * 2 * temp.marketing;
if(marketingAmt > 0){
payable(marketingWallet).sendValue(marketingAmt);
}
uint256 devAmt = unitBalance * 2 * temp.dev;
if(devAmt > 0){
payable(devWallet).sendValue(devAmt);
}
uint256 buybackAmt = unitBalance * 2 * temp.buyback;
if(buybackAmt > 0){
payable(buybackWallet).sendValue(buybackAmt);
}
}
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(router), tokenAmount);
// add the liquidity
router.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function swapTokensForBNB(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function setIsSniper(address adr, bool sniper) external onlyOwner{
isSniper[adr] = sniper;
}
function bulkExcludeFee(address[] memory accounts, bool state) external onlyOwner{
for(uint256 i = 0; i < accounts.length; i++){
_isExcludedFromFee[accounts[i]] = state;
}
}
function updateMarketingWallet(address newWallet) external onlyOwner{
marketingWallet = newWallet;
}
function updateDevWallet(address newWallet) external onlyOwner{
devWallet = newWallet;
}
function updateBuybackWallet(address newWallet) external onlyOwner{
buybackWallet = newWallet;
}
function updateCooldown(bool state, uint256 time) external onlyOwner{
coolDownTime = time * 1 seconds;
coolDownEnabled = state;
}
function updateSwapTokensAtAmount(uint256 amount) external onlyOwner{
swapTokensAtAmount = amount * 10**_decimals;
}
function updateSwapEnabled(bool _enabled) external onlyOwner{
swapEnabled = _enabled;
}
function updateAllowedTransfer(address account, bool state) external onlyOwner{
allowedTransfer[account] = state;
}
function updateMaxTxLimit(uint256 maxBuy, uint256 maxSell) external onlyOwner{
maxBuyLimit = maxBuy * 10**decimals();
maxSellLimit = maxSell * 10**decimals();
}
function updateMaxWalletlimit(uint256 amount) external onlyOwner{
maxWalletLimit = amount * 10**decimals();
}
function updateRouterAndPair(address newRouter, address newPair) external onlyOwner{
router = IRouter(newRouter);
pair = newPair;
}
//Use this in case BNB are sent to the contract by mistake
function rescueBNB(uint256 weiAmount) external onlyOwner{
require(address(this).balance >= weiAmount, "insufficient BNB balance");
payable(msg.sender).transfer(weiAmount);
}
function rescueAnyBEP20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
IERC20(_tokenAddr).transfer(_to, _amount);
}
receive() external payable{
}
} | _tokenTransfer | function _tokenTransfer(address sender, address recipient, uint256 tAmount, bool takeFee, bool isSell) private {
valuesFromGetValues memory s = _getValues(tAmount, takeFee, isSell);
if (_isExcluded[sender] ) { //from excluded
_tOwned[sender] = _tOwned[sender]-tAmount;
}
if (_isExcluded[recipient]) { //to excluded
_tOwned[recipient] = _tOwned[recipient]+s.tTransferAmount;
}
_rOwned[sender] = _rOwned[sender]-s.rAmount;
_rOwned[recipient] = _rOwned[recipient]+s.rTransferAmount;
if(s.rRfi > 0 || s.tRfi > 0) _reflectRfi(s.rRfi, s.tRfi);
if(s.rLiquidity > 0 || s.tLiquidity > 0) {
_takeLiquidity(s.rLiquidity,s.tLiquidity);
emit Transfer(sender, address(this), s.tLiquidity + s.tMarketing + s.tDev+ s.tBuyback);
}
if(s.rMarketing > 0 || s.tMarketing > 0) _takeMarketing(s.rMarketing, s.tMarketing);
if(s.rBuyback > 0 || s.tBuyback > 0) _takeBuyback(s.rBuyback, s.tBuyback);
if(s.rDev > 0 || s.tDev > 0) _takeDev(s.rDev, s.tDev);
emit Transfer(sender, recipient, s.tTransferAmount);
}
| //this method is responsible for taking all fee, if takeFee is true | LineComment | v0.8.7+commit.e28d00a7 | None | ipfs://da73f3f16b109b70329266f2661ff6afbd2a2b9bd4661a751b78d4f9ee193a54 | {
"func_code_index": [
15712,
16932
]
} | 8,275 |
||
RocketFuelV2 | RocketFuelV2.sol | 0x6f8655032885e22268a74703b76b43db0acef582 | Solidity | RocketFuelV2 | contract RocketFuelV2 is Context, IERC20, Ownable {
using Address for address payable;
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;
mapping (address => bool) public allowedTransfer;
mapping (address => bool) isSniper;
address[] private _excluded;
bool public tradingEnabled = false;
bool public swapEnabled = true;
bool private swapping;
//Anti Dump
mapping(address => uint256) private _lastSell;
bool public coolDownEnabled = true;
uint256 public coolDownTime = 30 seconds;
modifier antiBot(address account){
require(tradingEnabled || allowedTransfer[account], "Trading not enabled yet");
_;
}
IRouter public router;
address public pair;
uint8 private constant _decimals = 9;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1e15 * 10**_decimals;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 public swapTokensAtAmount = 1_000_000_000_000 * 10**9;
uint256 public maxBuyLimit = 5_000_000_000_000 * 10**9;
uint256 public maxSellLimit = 5_000_000_000_000 * 10**9;
uint256 public maxWalletLimit = 20_000_000_000_000 * 10**9;
uint256 public genesis_block;
address marketingWallet;
address devWallet;
address buybackWallet;
string private constant _name = "Rocket Fuel V2";
string private constant _symbol = "RKTF";
struct Taxes {
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
Taxes public taxes = Taxes(2, 7, 0, 3, 0);
Taxes public sellTaxes = Taxes(2, 7, 3, 0, 0);
struct TotFeesPaidStruct{
uint256 rfi;
uint256 marketing;
uint256 liquidity;
uint256 dev;
uint256 buyback;
}
TotFeesPaidStruct public totFeesPaid;
struct valuesFromGetValues{
uint256 rAmount;
uint256 rTransferAmount;
uint256 rRfi;
uint256 rMarketing;
uint256 rLiquidity;
uint256 rDev;
uint256 rBuyback;
uint256 tTransferAmount;
uint256 tRfi;
uint256 tMarketing;
uint256 tLiquidity;
uint256 tDev;
uint256 tBuyback;
}
event FeesChanged();
event UpdatedRouter(address oldRouter, address newRouter);
modifier lockTheSwap {
swapping = true;
_;
swapping = false;
}
constructor (address routerAddress) {
IRouter _router = IRouter(routerAddress);
address _pair = IFactory(_router.factory())
.createPair(address(this), _router.WETH());
router = _router;
pair = _pair;
excludeFromReward(pair);
_rOwned[owner()] = _rTotal;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[marketingWallet] = true;
_isExcludedFromFee[devWallet] = true;
_isExcludedFromFee[buybackWallet] = true;
allowedTransfer[address(this)] = true;
allowedTransfer[owner()] = true;
allowedTransfer[pair] = true;
allowedTransfer[marketingWallet] = true;
allowedTransfer[devWallet] = true;
allowedTransfer[buybackWallet] = true;
emit Transfer(address(0), owner(), _tTotal);
}
//std ERC20:
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
//override ERC20:
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 allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override antiBot(msg.sender) returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override antiBot(sender) returns (bool) {
require(!isSniper[sender], "Address is Sniper");
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public antiBot(msg.sender) returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public antiBot(msg.sender) returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function transfer(address recipient, uint256 amount) public override antiBot(msg.sender) returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tAmount, bool deductTransferRfi) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferRfi) {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rAmount;
} else {
valuesFromGetValues memory s = _getValues(tAmount, true, false);
return s.rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount/currentRate;
}
//@dev kept original RFI naming -> "reward" as in reflection
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is not excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function launch() public onlyOwner{
tradingEnabled = true;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function setTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
taxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function setSellTaxes(uint256 _rfi, uint256 _marketing, uint256 _liquidity, uint256 _dev, uint256 _buyback) public onlyOwner {
sellTaxes = Taxes(_rfi,_marketing,_liquidity,_dev,_buyback);
emit FeesChanged();
}
function _reflectRfi(uint256 rRfi, uint256 tRfi) private {
_rTotal -=rRfi;
totFeesPaid.rfi +=tRfi;
}
function _takeLiquidity(uint256 rLiquidity, uint256 tLiquidity) private {
totFeesPaid.liquidity +=tLiquidity;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tLiquidity;
}
_rOwned[address(this)] +=rLiquidity;
}
function _takeMarketing(uint256 rMarketing, uint256 tMarketing) private {
totFeesPaid.marketing +=tMarketing;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tMarketing;
}
_rOwned[address(this)] +=rMarketing;
}
function _takeDev(uint256 rDev, uint256 tDev) private {
totFeesPaid.dev +=tDev;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tDev;
}
_rOwned[address(this)] +=rDev;
}
function _takeBuyback(uint256 rBuyback, uint256 tBuyback) private {
totFeesPaid.buyback +=tBuyback;
if(_isExcluded[address(this)])
{
_tOwned[address(this)]+=tBuyback;
}
_rOwned[address(this)] +=rBuyback;
}
function _getValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory to_return) {
to_return = _getTValues(tAmount, takeFee, isSell);
(to_return.rAmount, to_return.rTransferAmount, to_return.rRfi, to_return.rMarketing, to_return.rLiquidity) = _getRValues1(to_return, tAmount, takeFee, _getRate());
(to_return.rDev, to_return.rBuyback) = _getRValues2(to_return, takeFee, _getRate());
return to_return;
}
function _getTValues(uint256 tAmount, bool takeFee, bool isSell) private view returns (valuesFromGetValues memory s) {
if(!takeFee) {
s.tTransferAmount = tAmount;
return s;
}
Taxes memory temp;
if(isSell) temp = sellTaxes;
else temp = taxes;
s.tRfi = tAmount*temp.rfi/100;
s.tMarketing = tAmount*temp.marketing/100;
s.tLiquidity = tAmount*temp.liquidity/100;
s.tDev = tAmount*temp.dev/100;
s.tBuyback = tAmount*temp.buyback/100;
s.tTransferAmount = tAmount-s.tRfi-s.tMarketing-s.tLiquidity-s.tDev-s.tBuyback;
return s;
}
function _getRValues1(valuesFromGetValues memory s, uint256 tAmount, bool takeFee, uint256 currentRate) private pure returns (uint256 rAmount, uint256 rTransferAmount, uint256 rRfi,uint256 rMarketing, uint256 rLiquidity){
rAmount = tAmount*currentRate;
if(!takeFee) {
return(rAmount, rAmount, 0,0,0);
}
rRfi = s.tRfi*currentRate;
rMarketing = s.tMarketing*currentRate;
rLiquidity = s.tLiquidity*currentRate;
uint256 rDev = s.tDev*currentRate;
uint256 rBuyback = s.tBuyback*currentRate;
rTransferAmount = rAmount-rRfi-rMarketing-rLiquidity-rDev-rBuyback;
return (rAmount, rTransferAmount, rRfi,rMarketing,rLiquidity);
}
function _getRValues2(valuesFromGetValues memory s, bool takeFee, uint256 currentRate) private pure returns (uint256 rDev,uint256 rBuyback) {
if(!takeFee) {
return(0,0);
}
rDev = s.tDev*currentRate;
rBuyback = s.tBuyback*currentRate;
return (rDev,rBuyback);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply/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-_rOwned[_excluded[i]];
tSupply = tSupply-_tOwned[_excluded[i]];
}
if (rSupply < _rTotal/_tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from),"You are trying to transfer more than your balance");
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
require(tradingEnabled, "Trading not active");
}
if(!_isExcludedFromFee[from] && !_isExcludedFromFee[to] && block.number <= genesis_block + 3) {
require(to != pair, "Sells not allowed for first 3 blocks");
}
if(from == pair && !_isExcludedFromFee[to] && !swapping){
require(amount <= maxBuyLimit, "You are exceeding maxBuyLimit");
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(from != pair && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && !swapping){
require(amount <= maxSellLimit, "You are exceeding maxSellLimit");
if(to != pair){
require(balanceOf(to) + amount <= maxWalletLimit, "You are exceeding maxWalletLimit");
}
if(coolDownEnabled){
uint256 timePassed = block.timestamp - _lastSell[from];
require(timePassed >= coolDownTime, "Cooldown enabled");
_lastSell[from] = block.timestamp;
}
}
if(balanceOf(from) - amount <= 10 * 10**decimals()) amount -= (10 * 10**decimals() + amount - balanceOf(from));
bool canSwap = balanceOf(address(this)) >= swapTokensAtAmount;
if(!swapping && swapEnabled && canSwap && from != pair && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]){
if(to == pair) swapAndLiquify(swapTokensAtAmount, sellTaxes);
else swapAndLiquify(swapTokensAtAmount, taxes);
}
bool takeFee = true;
bool isSell = false;
if(swapping || _isExcludedFromFee[from] || _isExcludedFromFee[to]) takeFee = false;
if(to == pair) isSell = true;
_tokenTransfer(from, to, amount, takeFee, isSell);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 tAmount, bool takeFee, bool isSell) private {
valuesFromGetValues memory s = _getValues(tAmount, takeFee, isSell);
if (_isExcluded[sender] ) { //from excluded
_tOwned[sender] = _tOwned[sender]-tAmount;
}
if (_isExcluded[recipient]) { //to excluded
_tOwned[recipient] = _tOwned[recipient]+s.tTransferAmount;
}
_rOwned[sender] = _rOwned[sender]-s.rAmount;
_rOwned[recipient] = _rOwned[recipient]+s.rTransferAmount;
if(s.rRfi > 0 || s.tRfi > 0) _reflectRfi(s.rRfi, s.tRfi);
if(s.rLiquidity > 0 || s.tLiquidity > 0) {
_takeLiquidity(s.rLiquidity,s.tLiquidity);
emit Transfer(sender, address(this), s.tLiquidity + s.tMarketing + s.tDev+ s.tBuyback);
}
if(s.rMarketing > 0 || s.tMarketing > 0) _takeMarketing(s.rMarketing, s.tMarketing);
if(s.rBuyback > 0 || s.tBuyback > 0) _takeBuyback(s.rBuyback, s.tBuyback);
if(s.rDev > 0 || s.tDev > 0) _takeDev(s.rDev, s.tDev);
emit Transfer(sender, recipient, s.tTransferAmount);
}
function swapAndLiquify(uint256 contractBalance, Taxes memory temp) private lockTheSwap{
uint256 denominator = (temp.liquidity + temp.marketing + temp.dev + temp.buyback) * 2;
uint256 tokensToAddLiquidityWith = contractBalance * temp.liquidity / denominator;
uint256 toSwap = contractBalance - tokensToAddLiquidityWith;
uint256 initialBalance = address(this).balance;
swapTokensForBNB(toSwap);
uint256 deltaBalance = address(this).balance - initialBalance;
uint256 unitBalance= deltaBalance / (denominator - temp.liquidity);
uint256 bnbToAddLiquidityWith = unitBalance * temp.liquidity;
if(bnbToAddLiquidityWith > 0){
// Add liquidity to pancake
addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith);
}
uint256 marketingAmt = unitBalance * 2 * temp.marketing;
if(marketingAmt > 0){
payable(marketingWallet).sendValue(marketingAmt);
}
uint256 devAmt = unitBalance * 2 * temp.dev;
if(devAmt > 0){
payable(devWallet).sendValue(devAmt);
}
uint256 buybackAmt = unitBalance * 2 * temp.buyback;
if(buybackAmt > 0){
payable(buybackWallet).sendValue(buybackAmt);
}
}
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(router), tokenAmount);
// add the liquidity
router.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function swapTokensForBNB(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function setIsSniper(address adr, bool sniper) external onlyOwner{
isSniper[adr] = sniper;
}
function bulkExcludeFee(address[] memory accounts, bool state) external onlyOwner{
for(uint256 i = 0; i < accounts.length; i++){
_isExcludedFromFee[accounts[i]] = state;
}
}
function updateMarketingWallet(address newWallet) external onlyOwner{
marketingWallet = newWallet;
}
function updateDevWallet(address newWallet) external onlyOwner{
devWallet = newWallet;
}
function updateBuybackWallet(address newWallet) external onlyOwner{
buybackWallet = newWallet;
}
function updateCooldown(bool state, uint256 time) external onlyOwner{
coolDownTime = time * 1 seconds;
coolDownEnabled = state;
}
function updateSwapTokensAtAmount(uint256 amount) external onlyOwner{
swapTokensAtAmount = amount * 10**_decimals;
}
function updateSwapEnabled(bool _enabled) external onlyOwner{
swapEnabled = _enabled;
}
function updateAllowedTransfer(address account, bool state) external onlyOwner{
allowedTransfer[account] = state;
}
function updateMaxTxLimit(uint256 maxBuy, uint256 maxSell) external onlyOwner{
maxBuyLimit = maxBuy * 10**decimals();
maxSellLimit = maxSell * 10**decimals();
}
function updateMaxWalletlimit(uint256 amount) external onlyOwner{
maxWalletLimit = amount * 10**decimals();
}
function updateRouterAndPair(address newRouter, address newPair) external onlyOwner{
router = IRouter(newRouter);
pair = newPair;
}
//Use this in case BNB are sent to the contract by mistake
function rescueBNB(uint256 weiAmount) external onlyOwner{
require(address(this).balance >= weiAmount, "insufficient BNB balance");
payable(msg.sender).transfer(weiAmount);
}
function rescueAnyBEP20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
IERC20(_tokenAddr).transfer(_to, _amount);
}
receive() external payable{
}
} | rescueBNB | function rescueBNB(uint256 weiAmount) external onlyOwner{
require(address(this).balance >= weiAmount, "insufficient BNB balance");
payable(msg.sender).transfer(weiAmount);
}
| //Use this in case BNB are sent to the contract by mistake | LineComment | v0.8.7+commit.e28d00a7 | None | ipfs://da73f3f16b109b70329266f2661ff6afbd2a2b9bd4661a751b78d4f9ee193a54 | {
"func_code_index": [
21172,
21373
]
} | 8,276 |
||
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | Ownable | 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);
_;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | Ownable | function Ownable() public {
owner = msg.sender;
}
| /**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
336,
396
]
} | 8,277 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | 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 Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
89,
266
]
} | 8,278 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | 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 Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
350,
630
]
} | 8,279 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
744,
860
]
} | 8,280 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
924,
1054
]
} | 8,281 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | TokenVesting | contract TokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
require(token.transfer(beneficiary, unreleased));
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
require(token.transfer(owner, refund));
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
} | /**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/ | NatSpecMultiLine | TokenVesting | function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
| /**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
1048,
1436
]
} | 8,282 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | TokenVesting | contract TokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
require(token.transfer(beneficiary, unreleased));
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
require(token.transfer(owner, refund));
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
} | /**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/ | NatSpecMultiLine | release | function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
require(token.transfer(beneficiary, unreleased));
emit Released(unreleased);
}
| /**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
1560,
1843
]
} | 8,283 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | TokenVesting | contract TokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
require(token.transfer(beneficiary, unreleased));
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
require(token.transfer(owner, refund));
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
} | /**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/ | NatSpecMultiLine | revoke | function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
require(token.transfer(owner, refund));
emit Revoked();
}
| /**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
2055,
2419
]
} | 8,284 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | TokenVesting | contract TokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
require(token.transfer(beneficiary, unreleased));
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
require(token.transfer(owner, refund));
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
} | /**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/ | NatSpecMultiLine | releasableAmount | function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
| /**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
2576,
2713
]
} | 8,285 |
|
TokenVesting | TokenVesting.sol | 0xdd2f263fe642769b3b3b9c164c565a16beb508a0 | Solidity | TokenVesting | contract TokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
require(token.transfer(beneficiary, unreleased));
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
require(token.transfer(owner, refund));
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
} | /**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/ | NatSpecMultiLine | vestedAmount | function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
| /**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://7063eb0d7b7ec16be1eb99c49ee9f6d6b1547011de2e7d1f16e4ea6509a6342a | {
"func_code_index": [
2841,
3292
]
} | 8,286 |
|
BlocBurgers | contracts/BlocBurgers.sol | 0x58d2035cc2aa0d9d8b8a02b1192bf20d17bf726f | Solidity | BlocBurgers | contract BlocBurgers is ERC721Enumerable, Ownable {
using SafeMath for uint256;
uint256 public ticketCounter = 0;
uint256 public reservationPrice = 0.069 ether;
uint256 public maxReservePerTransaction = 20;
uint256 public maxReservePublic = 40;
uint256 public maxReservePresale = 2;
uint256 public maxTotalSupply = 4200;
bool public presaleAllowed = false;
bool public publicSaleAllowed = false;
bool public publicClaimAllowed = false;
bool public provenanceHashLocked = false;
mapping(address => uint256) public reservedPresaleClaims;
mapping(address => uint256) public reservedPublicClaims;
mapping(address => uint256) public presaleClaimCounts;
mapping(address => uint256) public publicClaimCounts;
string public baseURI;
string public provenanceHash = "";
address private withdrawAddress = address(0);
bytes32 private merkleRoot;
constructor(string memory name, string memory symbol, address _withdrawAddress) ERC721(name, symbol) {
withdrawAddress = _withdrawAddress;
// allocate first to community
}
function reservePresale(uint256 reserveAmount, bytes32[] memory whitelistProof) external payable {
require(presaleAllowed, "Presale is disabled");
require(reserveAmount > 0, "Must reserve at least one");
require(ticketCounter.add(reserveAmount) <= maxTotalSupply, "Exceeds max supply");
require(reservationPrice.mul(reserveAmount) <= msg.value, "Ether value sent is not correct");
bytes32 addressBytes = keccak256(abi.encodePacked(_msgSender()));
require(MerkleProof.verify(whitelistProof, merkleRoot, addressBytes), "Invalid whitelist proof");
uint256 walletReservedClaims = reservedPresaleClaims[_msgSender()];
require(reserveAmount.add(walletReservedClaims) <= maxReservePresale, "Exceeds max presale allowed per wallet");
// increase reserved amount
reservedPresaleClaims[_msgSender()] = reserveAmount.add(walletReservedClaims);
// increase reserved tickets count
ticketCounter = ticketCounter.add(reserveAmount);
}
function reservePublic(uint256 reserveAmount) external payable {
require(publicSaleAllowed, "Public sale is disabled");
require(reserveAmount > 0, "Must reserve at least one");
require(reserveAmount <= maxReservePerTransaction, "Exceeds max allowed per transaction");
require(ticketCounter.add(reserveAmount) <= maxTotalSupply, "Exceeds max supply");
require(reservationPrice.mul(reserveAmount) <= msg.value, "Ether value sent is not correct");
uint256 walletReservedClaims = reservedPublicClaims[_msgSender()];
require(reserveAmount.add(walletReservedClaims) <= maxReservePublic, "Exceeds max public allowed per wallet");
// increase reserved amount
reservedPublicClaims[_msgSender()] = reserveAmount.add(walletReservedClaims);
// increase reserved tickets count
ticketCounter = ticketCounter.add(reserveAmount);
}
function reservePrivate(uint256 reserveAmount, address reserveAddress) external onlyOwner {
require(ticketCounter.add(reserveAmount) <= maxTotalSupply, "Exceeds max supply");
// increase reserved amount
reservedPublicClaims[reserveAddress] = reserveAmount.add(reservedPublicClaims[reserveAddress]);
// increase reserved tickets count
ticketCounter = ticketCounter.add(reserveAmount);
}
function claimPresale() external {
require(presaleAllowed, "Presale is disabled");
uint256 walletReservedPresaleClaims = reservedPresaleClaims[_msgSender()];
uint256 walletPresaleClaimCount = presaleClaimCounts[_msgSender()];
require(walletPresaleClaimCount < walletReservedPresaleClaims, "Nothing to claim");
for (uint256 i = 0; i < walletReservedPresaleClaims.sub(walletPresaleClaimCount); i++) {
uint256 mintIndex = totalSupply().add(1);
presaleClaimCounts[_msgSender()] = presaleClaimCounts[_msgSender()].add(1);
_safeMint(_msgSender(), mintIndex);
}
}
// public sale means all claims are available, no need to check presale state
function claimAll() external {
require(publicClaimAllowed, "Public claim is disabled");
uint256 walletReservedPresaleClaims = reservedPresaleClaims[_msgSender()];
uint256 walletReservedPublicClaims = reservedPublicClaims[_msgSender()];
uint256 walletPublicClaimCount = publicClaimCounts[_msgSender()];
uint256 walletPresaleClaimCount = presaleClaimCounts[_msgSender()];
uint256 totalReserved = walletReservedPublicClaims.add(walletReservedPresaleClaims);
uint256 totalClaimed = walletPublicClaimCount.add(walletPresaleClaimCount);
require(totalClaimed < totalReserved, "Nothing to claim");
for (uint256 i = 0; i < walletReservedPresaleClaims.sub(walletPresaleClaimCount); i++) {
uint256 mintIndex = totalSupply().add(1);
presaleClaimCounts[_msgSender()] = presaleClaimCounts[_msgSender()].add(1);
_safeMint(_msgSender(), mintIndex);
}
for (uint256 i = 0; i < walletReservedPublicClaims.sub(walletPublicClaimCount); i++) {
uint256 mintIndex = totalSupply().add(1);
publicClaimCounts[_msgSender()] = publicClaimCounts[_msgSender()].add(1);
_safeMint(_msgSender(), mintIndex);
}
}
function setReservationPrice(uint256 _price) external onlyOwner {
reservationPrice = _price;
}
function setMaxTotalSupply(uint256 _maxValue) external onlyOwner {
maxTotalSupply = _maxValue;
}
function setMaxReservePresale(uint256 _maxValue) external onlyOwner {
maxReservePresale = _maxValue;
}
function setMaxReservePublic(uint256 _maxValue) external onlyOwner {
maxReservePublic = _maxValue;
}
function setPresaleAllowed(bool _allowed) external onlyOwner {
presaleAllowed = _allowed;
}
function setPublicSaleAllowed(bool _allowed) external onlyOwner {
publicSaleAllowed = _allowed;
}
function setPublicClaimAllowed(bool _allowed) external onlyOwner {
publicClaimAllowed = _allowed;
}
function setMaxReservePerTransaction(uint256 _maxValue) external onlyOwner {
maxReservePerTransaction = _maxValue;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
function burn(uint256 tokenId) external {
require(_isApprovedOrOwner(msg.sender, tokenId), "Token not owned or approved");
_burn(tokenId);
}
function withdraw() external onlyOwner {
require(withdrawAddress != address(0), "Withdraw address not set");
uint256 contractBalance = address(this).balance;
payable(withdrawAddress).transfer(contractBalance);
}
function setWithdrawAddress(address _newWithdrawAddress) external onlyOwner {
withdrawAddress = _newWithdrawAddress;
}
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
require(!provenanceHashLocked, "Provenance hash already locked");
provenanceHash = _provenanceHash;
}
function lockProvenanceHash() external onlyOwner {
require(!provenanceHashLocked, "Provenance hash already locked");
provenanceHashLocked = true;
}
function getAvailableClaims(address walletAddress) external view returns (uint256) {
uint256 walletReservedPresaleClaims = reservedPresaleClaims[walletAddress];
uint256 walletReservedPublicClaims = reservedPublicClaims[walletAddress];
uint256 walletPublicClaimCount = publicClaimCounts[walletAddress];
uint256 walletPresaleClaimCount = presaleClaimCounts[walletAddress];
uint256 totalReserved = walletReservedPublicClaims.add(walletReservedPresaleClaims);
uint256 totalClaimed = walletPublicClaimCount.add(walletPresaleClaimCount);
return totalReserved.sub(totalClaimed);
}
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
} | /*
████████████████████
██ ██
██ ██ ██ ██
██ ████ ████ ██
██ ████ ██
██ ██
████████████████████████████████████
██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓██
████████████████████████████████
██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░██
██░░██░░░░██████░░░░░░██░░░░████
████ ████ ██████ ████ ██
██ ██
████████████████████████████
████████╗██╗████████╗ ██████╗ ██╗ ██╗ █████╗ ███████╗ ██╗ ██╗███████╗██████╗ ███████╗
╚══██╔══╝██║╚══██╔══╝██╔═══██╗ ██║ ██║██╔══██╗██╔════╝ ██║ ██║██╔════╝██╔══██╗██╔════╝
██║ ██║ ██║ ██║ ██║ ██║ █╗ ██║███████║███████╗ ███████║█████╗ ██████╔╝█████╗
██║ ██║ ██║ ██║ ██║ ██║███╗██║██╔══██║╚════██║ ██╔══██║██╔══╝ ██╔══██╗██╔══╝
██║ ██║ ██║ ╚██████╔╝ ╚███╔███╔╝██║ ██║███████║ ██║ ██║███████╗██║ ██║███████╗
╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝
*/ | Comment | claimAll | function claimAll() external {
require(publicClaimAllowed, "Public claim is disabled");
uint256 walletReservedPresaleClaims = reservedPresaleClaims[_msgSender()];
uint256 walletReservedPublicClaims = reservedPublicClaims[_msgSender()];
uint256 walletPublicClaimCount = publicClaimCounts[_msgSender()];
uint256 walletPresaleClaimCount = presaleClaimCounts[_msgSender()];
uint256 totalReserved = walletReservedPublicClaims.add(walletReservedPresaleClaims);
uint256 totalClaimed = walletPublicClaimCount.add(walletPresaleClaimCount);
require(totalClaimed < totalReserved, "Nothing to claim");
for (uint256 i = 0; i < walletReservedPresaleClaims.sub(walletPresaleClaimCount); i++) {
uint256 mintIndex = totalSupply().add(1);
presaleClaimCounts[_msgSender()] = presaleClaimCounts[_msgSender()].add(1);
_safeMint(_msgSender(), mintIndex);
}
for (uint256 i = 0; i < walletReservedPublicClaims.sub(walletPublicClaimCount); i++) {
uint256 mintIndex = totalSupply().add(1);
publicClaimCounts[_msgSender()] = publicClaimCounts[_msgSender()].add(1);
_safeMint(_msgSender(), mintIndex);
}
}
| // public sale means all claims are available, no need to check presale state | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
4232,
5491
]
} | 8,287 |
||
Dalmatians | @openzeppelin/contracts/access/Ownable.sol | 0x2544cde635fab0a56202dbfe4feab2ec40eef3ab | Solidity | Ownable | 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;
}
} | /**
* @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.
*/ | NatSpecMultiLine | owner | function owner() public view virtual returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://4aec117c3c6006628e910a5c206f5e5a428ce1b67d6025e9a69f46b58113026d | {
"func_code_index": [
530,
622
]
} | 8,288 |
Dalmatians | @openzeppelin/contracts/access/Ownable.sol | 0x2544cde635fab0a56202dbfe4feab2ec40eef3ab | Solidity | Ownable | 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;
}
} | /**
* @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.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @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.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://4aec117c3c6006628e910a5c206f5e5a428ce1b67d6025e9a69f46b58113026d | {
"func_code_index": [
1181,
1334
]
} | 8,289 |
Dalmatians | @openzeppelin/contracts/access/Ownable.sol | 0x2544cde635fab0a56202dbfe4feab2ec40eef3ab | Solidity | Ownable | 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;
}
} | /**
* @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.
*/ | NatSpecMultiLine | transferOwnership | 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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://4aec117c3c6006628e910a5c206f5e5a428ce1b67d6025e9a69f46b58113026d | {
"func_code_index": [
1484,
1770
]
} | 8,290 |
Dalmatians | @openzeppelin/contracts/access/Ownable.sol | 0x2544cde635fab0a56202dbfe4feab2ec40eef3ab | Solidity | Dalmatians | contract Dalmatians is ERC721, Ownable {
using SafeMath for uint256;
string public Dalmatians_PROVENANCE = "";
string public LICENSE_TEXT = "";
bool licenseLocked = false;
uint256 public Price = 10000000000000000; // 0.01 ETH
uint256 public constant MAX_Purchase = 50;
uint256 public constant MAX_Supply = 10001;
bool public saleIsActive = false;
event licenseisLocked(string _licenseText);
constructor() ERC721("Dalmatians", "Dal") {}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
function reserve() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 20; i++) {
_safeMint(msg.sender, supply + i);
}
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
Dalmatians_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function tokensOfOwner(address _owner) external view returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
}
else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// Returns the license for tokens
function tokenLicense(uint256 _id) public view returns (string memory) {
require(_id < totalSupply(), "CHOOSE A Dalmatian WITHIN RANGE");
return LICENSE_TEXT;
}
// Locks the license to prevent further changes
function lockLicense() public onlyOwner {
licenseLocked = true;
emit licenseisLocked(LICENSE_TEXT);
}
// Change the license
function changeLicense(string memory _license) public onlyOwner {
require(licenseLocked == false, "License already locked");
LICENSE_TEXT = _license;
}
function mint(uint256 numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Dalmatians");
require(numberOfTokens > 0 && numberOfTokens <= MAX_Purchase, "Can only mint 50 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_Supply, "Purchase would exceed max supply of Dalmatians");
require(msg.value >= Price.mul(numberOfTokens), "Ether value sent is not correct");
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_Supply) {
_safeMint(msg.sender, mintIndex);
}
}
}
function setPrice(uint256 newPrice) public onlyOwner {
Price = newPrice;
}
} | tokenLicense | function tokenLicense(uint256 _id) public view returns (string memory) {
require(_id < totalSupply(), "CHOOSE A Dalmatian WITHIN RANGE");
return LICENSE_TEXT;
}
| // Returns the license for tokens | LineComment | v0.7.0+commit.9e61f92b | None | ipfs://4aec117c3c6006628e910a5c206f5e5a428ce1b67d6025e9a69f46b58113026d | {
"func_code_index": [
1766,
1954
]
} | 8,291 |
||
Dalmatians | @openzeppelin/contracts/access/Ownable.sol | 0x2544cde635fab0a56202dbfe4feab2ec40eef3ab | Solidity | Dalmatians | contract Dalmatians is ERC721, Ownable {
using SafeMath for uint256;
string public Dalmatians_PROVENANCE = "";
string public LICENSE_TEXT = "";
bool licenseLocked = false;
uint256 public Price = 10000000000000000; // 0.01 ETH
uint256 public constant MAX_Purchase = 50;
uint256 public constant MAX_Supply = 10001;
bool public saleIsActive = false;
event licenseisLocked(string _licenseText);
constructor() ERC721("Dalmatians", "Dal") {}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
function reserve() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 20; i++) {
_safeMint(msg.sender, supply + i);
}
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
Dalmatians_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function tokensOfOwner(address _owner) external view returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
}
else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// Returns the license for tokens
function tokenLicense(uint256 _id) public view returns (string memory) {
require(_id < totalSupply(), "CHOOSE A Dalmatian WITHIN RANGE");
return LICENSE_TEXT;
}
// Locks the license to prevent further changes
function lockLicense() public onlyOwner {
licenseLocked = true;
emit licenseisLocked(LICENSE_TEXT);
}
// Change the license
function changeLicense(string memory _license) public onlyOwner {
require(licenseLocked == false, "License already locked");
LICENSE_TEXT = _license;
}
function mint(uint256 numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Dalmatians");
require(numberOfTokens > 0 && numberOfTokens <= MAX_Purchase, "Can only mint 50 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_Supply, "Purchase would exceed max supply of Dalmatians");
require(msg.value >= Price.mul(numberOfTokens), "Ether value sent is not correct");
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_Supply) {
_safeMint(msg.sender, mintIndex);
}
}
}
function setPrice(uint256 newPrice) public onlyOwner {
Price = newPrice;
}
} | lockLicense | function lockLicense() public onlyOwner {
licenseLocked = true;
emit licenseisLocked(LICENSE_TEXT);
}
| // Locks the license to prevent further changes | LineComment | v0.7.0+commit.9e61f92b | None | ipfs://4aec117c3c6006628e910a5c206f5e5a428ce1b67d6025e9a69f46b58113026d | {
"func_code_index": [
2010,
2139
]
} | 8,292 |
||
Dalmatians | @openzeppelin/contracts/access/Ownable.sol | 0x2544cde635fab0a56202dbfe4feab2ec40eef3ab | Solidity | Dalmatians | contract Dalmatians is ERC721, Ownable {
using SafeMath for uint256;
string public Dalmatians_PROVENANCE = "";
string public LICENSE_TEXT = "";
bool licenseLocked = false;
uint256 public Price = 10000000000000000; // 0.01 ETH
uint256 public constant MAX_Purchase = 50;
uint256 public constant MAX_Supply = 10001;
bool public saleIsActive = false;
event licenseisLocked(string _licenseText);
constructor() ERC721("Dalmatians", "Dal") {}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
function reserve() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 20; i++) {
_safeMint(msg.sender, supply + i);
}
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
Dalmatians_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function tokensOfOwner(address _owner) external view returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
}
else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// Returns the license for tokens
function tokenLicense(uint256 _id) public view returns (string memory) {
require(_id < totalSupply(), "CHOOSE A Dalmatian WITHIN RANGE");
return LICENSE_TEXT;
}
// Locks the license to prevent further changes
function lockLicense() public onlyOwner {
licenseLocked = true;
emit licenseisLocked(LICENSE_TEXT);
}
// Change the license
function changeLicense(string memory _license) public onlyOwner {
require(licenseLocked == false, "License already locked");
LICENSE_TEXT = _license;
}
function mint(uint256 numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Dalmatians");
require(numberOfTokens > 0 && numberOfTokens <= MAX_Purchase, "Can only mint 50 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_Supply, "Purchase would exceed max supply of Dalmatians");
require(msg.value >= Price.mul(numberOfTokens), "Ether value sent is not correct");
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_Supply) {
_safeMint(msg.sender, mintIndex);
}
}
}
function setPrice(uint256 newPrice) public onlyOwner {
Price = newPrice;
}
} | changeLicense | function changeLicense(string memory _license) public onlyOwner {
require(licenseLocked == false, "License already locked");
LICENSE_TEXT = _license;
}
| // Change the license | LineComment | v0.7.0+commit.9e61f92b | None | ipfs://4aec117c3c6006628e910a5c206f5e5a428ce1b67d6025e9a69f46b58113026d | {
"func_code_index": [
2169,
2348
]
} | 8,293 |
||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | uri | function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
| //URI for decoding storage of tokenIDs | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
873,
1036
]
} | 8,294 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | SpiritSeedMint | function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
| //Mints SpiritSeed Seeds | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
1067,
1954
]
} | 8,295 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | _beforeTokenTransfer | function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
| //Conforms to ERC-1155 Standard | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
1996,
2263
]
} | 8,296 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __batchTransfer | function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
| //Batch Transfers Tokens | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
2294,
2595
]
} | 8,297 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __reserveSeeds | function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
| //Reserves Seeds | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
2618,
2817
]
} | 8,298 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __setBaseURI | function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
| //Sets Base URI For .json hosting | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
2857,
2949
]
} | 8,299 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __setMaxSeeds | function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
| //Sets Max Seeds for future Seed Expansion Packs | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
3004,
3094
]
} | 8,300 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __setMaxSeedsPurchase | function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
| //Sets Max Seeds Purchaseable by Wallet | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
3140,
3265
]
} | 8,301 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __setSeedPrice | function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
| //Sets Future Seed Price | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
3296,
3390
]
} | 8,302 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __flip_allowMultiplePurchases | function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
| //Flips Allowing Multiple Purchases for future Seed Expansion Packs | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
3464,
3585
]
} | 8,303 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __flip_saleState | function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
| //Flips Sale State | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
3614,
3702
]
} | 8,304 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __withdraw | function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
| //Withdraws Ether from Contract | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
3740,
3839
]
} | 8,305 |
||||
SpiritSeed | contracts/SpiritSeed.sol | 0x9b07bb421df4e2d52d5997da54a99cff33d5ed6b | Solidity | SpiritSeed | contract SpiritSeed is ERC1155, Ownable, Pausable, ERC1155Burnable
{
using SafeMath for uint256;
//Initialization
string public constant name = "SpiritSeed";
string public constant symbol = "SEED";
string public _BASE_URI = "https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/";
//Token Amounts
uint256 public _SEEDS_MINTED = 0;
uint256 public _MAX_SEEDS = 100;
uint256 public _MAX_SEEDS_PURCHASE = 5;
//Price
uint256 public _SEED_PRICE = 0.55 ether;
//Sale State
bool public _SALE_IS_ACTIVE = false;
bool public _ALLOW_MULTIPLE_PURCHASES = false;
//Mint Mapping
mapping (address => bool) private minted;
//Constructor
constructor() ERC1155("https://ipfs.io/ipfs/QmXXAE5fQmPkx7Jkeoj1Kq6ANWSqVov5mCzgmAwf8Fmcxs/{id}.json") { }
//URI for decoding storage of tokenIDs
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, Strings.toString(tokenId), ".json"))); }
//Mints SpiritSeed Seeds
function SpiritSeedMint(uint numberOfTokens) public payable
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Seeds");
require(numberOfTokens <= _MAX_SEEDS_PURCHASE, "Can only mint 5 Seeds at a time");
require(_SEEDS_MINTED.add(numberOfTokens) <= _MAX_SEEDS, "Purchase would exceed max supply of Seeds");
require(_SEED_PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct. 0.55 ETH Per Seed | 550000000000000000 WEI");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
//Mints Seeds
for(uint i = 0; i < numberOfTokens; i++)
{
if (_SEEDS_MINTED < _MAX_SEEDS)
{
_mint(msg.sender, _SEEDS_MINTED, 1, "");
_SEEDS_MINTED += 1;
}
}
minted[msg.sender] = true;
}
//Conforms to ERC-1155 Standard
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
//Batch Transfers Tokens
function __batchTransfer(address[] memory recipients, uint256[] memory tokenIDs, uint256[] memory amounts) public onlyOwner
{
for(uint i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
//Reserves Seeds
function __reserveSeeds(uint256 amt) public onlyOwner
{
for(uint i=0; i<amt; i++)
{
_mint(msg.sender, i, 1, "");
_SEEDS_MINTED += 1;
}
}
//Sets Base URI For .json hosting
function __setBaseURI(string memory BASE_URI) public onlyOwner { _BASE_URI = BASE_URI; }
//Sets Max Seeds for future Seed Expansion Packs
function __setMaxSeeds(uint256 MAX_SEEDS) public onlyOwner { _MAX_SEEDS = MAX_SEEDS; }
//Sets Max Seeds Purchaseable by Wallet
function __setMaxSeedsPurchase(uint256 MAX_SEEDS_PURCHASE) public onlyOwner { _MAX_SEEDS_PURCHASE = MAX_SEEDS_PURCHASE; }
//Sets Future Seed Price
function __setSeedPrice(uint256 SEED_PRICE) public onlyOwner { _SEED_PRICE = SEED_PRICE; }
//Flips Allowing Multiple Purchases for future Seed Expansion Packs
function __flip_allowMultiplePurchases() public onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
//Flips Sale State
function __flip_saleState() public onlyOwner { _SALE_IS_ACTIVE = !_SALE_IS_ACTIVE; }
//Withdraws Ether from Contract
function __withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); }
//Pauses Contract
function __pause() public onlyOwner { _pause(); }
//Unpauses Contract
function __unpause() public onlyOwner { _unpause(); }
} | __pause | function __pause() public onlyOwner { _pause(); }
| //Pauses Contract | LineComment | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
3863,
3916
]
} | 8,306 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.